Reputation: 7849
Is it better to declare variables at the beginning of the function or where I use them?
The advantage of declaring them at the beginning is that I can easily see the list of the local variables. But I read somewhere that this increase the likelihood of errors.
So, what's better?
In the case it's better to declare them at the beginning, should I always initialize them with a value?
Upvotes: 1
Views: 90
Reputation: 2971
Like Josh Bloch explains in his "Effective Java" you should declare locals only before you need the - to make code more readable, maintainable and prevent bugs.
It's also good practice to declare locals as final if they are not suposed to get an new object or a primitive value assigned again in its local context.
Upvotes: 0
Reputation: 3589
As methods should be short and therefore the number of local variables is rather small, it is in my opinion better to declare local variables right before using them (not all of them at the top).
They should, if possible, be initialized right away to enhance readability. If they are declared where they are needed, you can almost always initialize with a meaningful value, instead of null, 0 or "".
Upvotes: 4
Reputation: 1609
In some cases, the compiler forces you to assign a value Definite assignment analysis - Wikipedia, the free encyclopedia . In this case however, why initialize to 0 - just initialize the variable to the first assignment.
You dont need to initialize it right away, but YOU MUST, initialize it before it is used.
Upvotes: 2