Sunday, February 28, 2010

Keep It Local

Deciding whether a variable should be a member of a class or a local variable may not be clear to newer developers. I have always found the following rule of thumb to work best:
If it can be local, make it local.

That is, if at all possible, make the variable local. Making it a class member should be a last resort, not the default. Why should local be preferred over a class data member? For the same reason that local variables are preferred over global variables. Local variables are easier to understand. They only exist in the block they are defined in and can only directly influence code in this block. Data members exist for the entire lifetime of the object they are part of. Determining if they are initialized correctly and their effect requires one to look at every method of the class. In a multi-threaded environment, synchronization of access to data members is another complication that local variables do not have. Data members also increase the memory footprint of your objects.

Variables that should be data members are ones that hold the persistent state of the object that must be maintained between method calls. Variables that hold transient values that are only needed temporarily should be local variables.

So when reviewing a class, look carefully at each of its data members and be sure that you can justify why it's a data member and not a local variable. If you can't justify it, fix it.