java - Where shall variables be defined within a method? -


Suppose I have a way with the parameter of type object . The method returns nothing - zero .

First it checks that the parameter is not zero (or any other check, such as objectParam.isEnabled () )

  if (objectParam. IsEnabled ()) {// ok}  

Now, if the situation is satisfied, then I need a local variable. If it is not so, then I do not need any variables.

Where should I define them? Inside "scope" or just after the method header?

Of course, I can do it wherever I want, but by the way should a better practice?

I believe this is the best practice to declare as long as a variable That is, as much as you can do in tightly nested areas, start with a useful value.

This explains where and how it is being used - when you are looking at the code where it is used, you will not have to look far away to see the declaration.

In this particular case, I disagree with the official Java style guide - and this is how it blows. Effective Java, 2 versions, item 45:

The most powerful technique to reduce the scope of a local variable is to declare it when used first.

So if you do not need a variable unless you have executed some other statements, do not declare it.


Comments

Popular posts from this blog

c# - How to capture HTTP packet with SharpPcap -

php - Multiple Select with Explode: only returns the word "Array" -

php - jQuery AJAX Post not working -