This is the kind of code that I've come across a number of times during some of my code reviews...
Java
public void myMethod(MyObject myObj) {
/* code that doesn't reference myObj */
myObj = new MyObject();
/* code that manipulates myObj variable */
}
Then of course there is the method call to myMethod() that looks like this...
Java
myMethod(null);
So what's wrong with this?
1. No parameter scoped variable should ever be reassigned inside a method and in fact your parameters should be declared as final to prevent this.
2. Declaration of a variable should be done within its correct scope - if you intend to use a variable as a local variable, declare it so. In this case declaring the variable as a parameter implies that it's an input value that the method requires to run.
The problems identified above are quite severe, but I think the next problem with this code is the most important in this case -
3. Readability and maintainability. If someone comes along who has never seen this code before, they will naturally assume that the method requires some sort of input. This of course would be an incorrect assumption in this particular case, which in terms increases the complexity of what the developer has to keep in mind while working with this code. If this issue isn't fixed, the next developer that comes along faces the same challenge. This decreases productivity and makes it more difficult to maintain a good code base.
4. Of course don't forget the fact that you still need to pass some value when calling the method - a null in my example! This does mean the value goes on the stack and there is a little bit of memory and CPU cycles used for that, I wouldn't consider this as a real performance problem however, but it is wasteful.
So a few things to learn from the above, and just remember - declare variables only when you need to use them and not beyond that.
All code examples shown above have been obfuscated from their original versions but still show similarities in terms of style.
-i