Monday, August 9, 2010

Limit use of member variables in code-behind

I frequently come across code that looks something like this:

private int memberVariable;

private void StartHere() {
memberVariable=1;
}

private void RunFirst() {
memberVariable=2;
}

private void PrintResult() {
int result = memberVariable*4; //<--error on this line for example
}

Let's say there is an error on the line marked with the comment above. In troubleshooting the issue, it might be helpful to know what the value of memberVariable is. If I look at PrintResult(), I see a variable named "result" which is being defined as an int. But then I see it using "memberVariable" which is defined outside of PrintResult(). Since I didn't write this code, it is difficult for me to know what exactly memberVariable is at the time PrintResult() gets called. Did StartHere() get called before PrintResult()? Did RunFirst() get called? If both were called, which ran last?

It is much more desirable NOT to declare variables outside of the methods they are being used in. Of course there are some situations where you must do this kind of thing, but for the most part, you should be able to use variables inside methods by PASSING them to the method instead of relying on them being instanced and valued at some point before our method being called.