Veteran programmers surely encounter such situation where they spend countless hours tracking down a hard-to-fin bug that that is due to local variable having the same name as the instance/static variable in a class. In such case, the local variable will take precedent over instance variable which may not be the intention of the programmer.
Such case is especially prevalent in large class. Despite the best practice that emphasize that class should be kept as small as possible with some gurus setting a threshold of 200 line so that class is easily maintainable, in practice it often impractical for some classes as it creates more classes unnecessarily that results in higher memory consumption, reduced performance and make class navigation time-consuming. If one peruse many open-source projects, one will surely find certain classes having thousands of line of code. With more lines of code also means that the class will be error-prone to carelessness especially if the class is been maintained by many programmers. It is in this situation that name clash is likely the source of difficult bug.
Such name clash are common source of potential bug when local variable utilize the same name as instance variable whether by intention or by assumption. There will be tendency to use back the same name as instance variable for method argument (method argument is also local to method) or as local variable. Another caveat when one reuse local variable name that similar to instance variable name end up confusing himself, and end up periodically checking if the local variable is indeed been declared within the method. When class become large, such meticulous assurance that there is no name clash becomes time-consuming. In a team environment where many programmers fixing each other classes, such check becomes involving and time-wasting.
Quantifying local variable with underscore
So how do one resolve the name clash which may be the source of potential bug and confusion ? This could be done by simply prefix local variable/method argument with underscore eg _myName. In this way, one neither need to worry if there is any potential name clash nor check if a variable is local or instance by its declaration. Just by the name of variable will indicate its scope.
public class TestVariable
private static int seed = 1;
private static String data = “testing”;
private static String getResult(int _seed) // local
// See how easy to tell the scope of variable through its name
// It is a time-saver if the method and class are large
int _count = 20;
return data + (_seed * _count); // local & instance
public static void main(String _args)