ArticleS. MichaelFeathers.
TheReluctantGlobalVariable [add child]

The Reluctant Global Variable


I don’t know many people who hate global variables as much as I do. I guess it’s an occupational hazard. I spend a lot of time going around helping people get existing code under test and globals are often a pain in that regard. If you have a global which modifies state, you want to make sure that you have some way to reset it at the beginning of each test. If you don’t, you have a state-leak which could make your tests behave erratically.

The Singleton Design Pattern is the commonest expression of a global variable in OO systems, and it’s interesting to notice just how much it clashes with unit testing. Traditionally, a singleton has a private constructor and a public static getInstance method.


// A Classic Singleton

public class Router {
private static Router instance;

private Router() { ... }

public static Router getInstance() {
if (instance == null)
instance = new Router();
return instance;
}

public void route(Message message) { ... }

// all other methods
...

}


The two conspire together to make sure that you can only have one instance of the singleton, but they also leave you with a convenient way of making a global variable: all you have to do is call getInstance any place that you want to and you have your global. Now, in fairness, opinion in the industry has been moving toward using the singleton pattern just to ensure a single instance. There’s no reason why you have to call getInstance every time you use the singleton; you could just call it once and pass the object around. Unfortunately, few people do that. In many systems, you are pretty much stuck using various tricks to make code that uses your singletons testable. Here’s one:


public class Router {
private static Router instance;

protected Router() { ... }

public static Router getInstance() {
if (instance == null)
instance = new Router();
return instance;
}

public static void setTestingInstance(Router newInstance) {
instance = newInstance;
}

...
}


The setTestingInstance method allows you to swap out one singleton for another. Notice that the constructor is now protected also, so that the singleton can be subclassed to provide testing behavior. This solution isn’t great for everyone, but if you are one of the many people who use singleton not because you are terribly concerned about having more than one instance, but because it’s a convenient way of making a global variable, it’s a decent way to go. The thing is, once you’ve done that it’s legitimate to ask why you don’t you, as Uncle Bob put it: “just create one”?:


public class Router {
public static Router instance;
...
}


The only advantage that a singleton with a setTestingInstance method has over a public variable is that not everyone is going to realize that setTestingInstance is there. If you want to have the illusion of a classic singleton, you can preserve it somewhat.

All this is fine, but I think that the thing that is key to understand is something that Uncle Bob pointed out earlier: the classic singleton pattern mixes two concerns: it is a mechanism for ensuring a single instance, and a mechanism for creating a global variable. There are, sadly, some times when all you need is the global variable. Here’s one:

I’m creating a testing tool for writing tests while refactoring. The key abstraction is something called a Vise. You use a Vise to grip values and record them for testing. The Vise has to be accessible in any code that you are about to refactor, so you don’t have the luxury of passing it down some call chain. You need to be able to just plop it in your code and go. And, there is only going to be one of them. So, here’s how you would make a call to the Vise if it used the classic singleton pattern:


Vise.getInstance().grip(value);


The fact is, however, that there is going to be just one instance in typical usage, but it’s not a hard design constraint. It would actually be more convenient for users if the call could look like this:


Vise.instance.grip(value);


Or even this:


Vise.grip(value);


How do we do that and still keep a flexible design? Well, we could use the following little pattern:


public class Vise
{
public static IVise instance;
}

public interface IVise
{
void grip(Object object);
...
}


Here we have a class Vise, which really is nothing more than a holder for a static variable. Is that good? Well, it’s not great; it’s a global variable, but it is flexible. The type of the instance variable is IVise and IVise can be implemented by a wide variety of classes, each of which we can set as the Vise for a session.

In the case of my little testing tool, I ended up creating a Vise like this:


public class Vise
{
public static IVise vise = new DefaultVise(new InMemoryStore());
...
}


Vise also has a set of static methods which delegate to the IVise instance:


public class Vise
{
public static IVise vise = new DefaultVise(new InMemoryStore());

public static void grip(Object object) {
vise.grip(object);
}
...
}


And that enables a cleaner syntax while preserving flexibility:


Vise.grip(value);


So, this is just a variation of Uncle Bob's "Just Create One” pattern or Statically Initialized Non-Singleton (SINS) with an interface. The essence of it is this: if you need a global variable, and you aren’t concerned about malicious substitution at runtime, create a class which holds the variable publically. Consider making the type of the variable an interface so that you preserve your options: you can change the type of the actual class you use without impacting the variable’s clients.

One thing that is odd about it is that it is strange to have a situation where a class like, say, Vise, doesn’t implement IVise, but there’s no real need to. And, it’s very convenient to give the variable-holding class the general name; it becomes a known point of access in the system.


!commentForm

 Sun, 11 Jun 2006 08:18:22, Sebastian Kübeck, IVise?
No offense but I think you called the interface IVise because you didn't find a proper name for it.
For me, a name like that is a clue to a design smell somewhere.
I'd suggest either:


Toolbox.getVise().grip(value);


or you rename the interface to something more expressive, e.g.:

public class Vise
{
public static ViseMechanics mechanics = new DefaultViseMechanics(new InMemoryStore());

public static void grip(Object object) {
mechanics.grip(object);
}
...
}


BTW: I'm extremely curious about your test tool!

No offense taken. I really don't like to fall back on the -I- convention but I do when nothing else occurs to me. I like the mechanics name. I'll change it to that. Thanks. In another case where I used this pattern, I needed to talk to a device. So I had a concrete class Device and it held an instance of FITAccessibleDevice. BTW, I'll probably do an announce and release of the tool in a day or two. -- MichaelFeathers
 Sun, 11 Jun 2006 13:15:28, Sebastian Kübeck, Bet lost!
I had a bet with myself that you'll rather take the other approach....bet lost ;-)
BTW.: Could you show me a way to factor out the database stuff out of an active record?

http://www.martinfowler.com/eaaCatalog/activeRecord.html

I had to debug such masterpieces with some 10K lines of Java and PL/SQL each and I don't want to repeat
that experience :-(.

 Sun, 11 Jun 2006 22:44:15, David Chelimsky, factoring out from AR
I would just use Move Method to move the database stuff out, leaving a delegate for the clients of the model object:

public void insert()
{
persister.setSomeProperty(someProperty);
persister.setSomeOtherProperty(someOtherProperty);
persister.insert();
}


Too simplistic?
 Mon, 12 Jun 2006 12:44:59, MichaelFeathers,
Sebastian, yes, you can use 'move method' like David suggested, but beyond that, so much depends on where you want to go. Is a 'domain model' worthwhile, for instance? One trick that you can use with 'Active Record' is extract a superclass with the data and then look at replacing inheritance with delegation. If you have several contexts in which you use the active record, you may end up factoring into several classes which operate on the data class and a class which manages its storage and retrieval.
 Mon, 12 Jun 2006 16:18:06, Ben Fulton,
Any chance of adding more information to your RSS feed than just the title? It's not always that compelling :)

I'll see what we can do, Ben. Sheesh, I work hard on those titles. :) - MichaelFeathers
 Mon, 12 Jun 2006 20:48:30, Lionel Orellana, Singleton workaround with reflection

I like doing this with singletons:

if (instance == null){
string className = <get class name from a config file or the like>;
instance = <create an instance of className>;
}

You have to make the constructor protected too so there's not much difference, but I prefer this to calling a setTestingInstance method or setting the static variable ... gives me one less thing to worry about so I'm happy to take the overhead of reflection ...

That's nice if you have a config file in place.. there are many ways to handle the problem. I'd stop short of introducing one for that reason, though. That's just me. We all have to decide just how important the singleton property is in each case, and how closely we have to protect it. -- MichaelFeathers
 Tue, 13 Jun 2006 15:55:07, Sebastian Kübeck, Config File
Lionel! be careful with that config aproach! You add an "external" dependency there that your IDE cannot track.
Suppose you want to change the name of your class the you have change that in the config file too
while IDE could handle this when you had it in source.
It's not so bad when you have tests around but it can be annoying having lots of class names
around in config files and keeping them in sync with the source.

One thing you can do there is to have a type code in your config file instead.
Example:

You have some ViseMechanics[?] implementations:

interface ViseMechanics {
public String getName();
}

class DefaultViseMechanics implements ViseMechanics {
public String getName() {
return "default";
}
}

You can then use the prototype pattern to create an array...


ViseMechanics array[] = {new DefaultMechanics(), ...};


...and copy out the instance that fit's to the type code in the config file that
might looks like this:


currentViseMechanics=default

You could also use reflection to find all the ViseMechanics[?] instances instead of the the array.
With that, you don't have a dependency to the class name and can rename and move the class as you like.
 Tue, 13 Jun 2006 16:20:59, Sebastian Kübeck, Active Record
Thanks for the inspiration on the Active Record thing!
I'll make some experiments on a smaller classes to see where I end up.
 Thu, 29 Jun 2006 14:46:27, , IVise and ICaramba
I thought IVise would be a bad name for the interface, given the blog in which the ICaramba was mentioned.

Since them I've been naming my interfaces Caramba and my classes CarambaImpl[?].

Even in cases where Vise.grip( Object ) is a good alternative and therefore the class is called Vise, the interface would be called ViseIface[?].

So? Are we going to have a standard here or we are just going round in circles?
 Wed, 6 Sep 2006 22:22:50, Lionel Orellana, Hashtable for the prototypes
That's good Sebastian. You could use a hashtable instead of the array to map "default" with DefaultViseMechanics[?].
Cheers