Suppose, I have a method with a parameter of Object type.
The method returns nothing – void.
First it checks whether the parameter is not null (or any other check, like objectParam.isEnabled())
if (objectParam.isEnabled()) {
// ok
}
Now, if the condition is satisfied, I need local variables. If it’s not, then I don’t need any variables.
WHERE SHOULD I define them? Inside the “if scope” or just after the method header?
Of course, I can do it wherever I like, but which way should be a better practice?
I believe it’s best practice to declare a variable as late as you can, in the most tightly nested scope that you can, ideally at the point where it’s initialized with a useful value.
That makes it clearer where and how it’s going to be used – when you’re looking at the code where it’s used, you won’t have to look up very far to see the declaration.
In this particular case I disagree with the official Java Style Guide – and so does Josh Bloch. From Effective Java, 2nd edition, item 45:
So if you don’t need the variable until you’ve executed a few other statements, don’t declare it until that point.