1

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?

3 Answers 3

4

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 "".

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.