Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding local variable initialization

I'm reading J. Bloch's effective Java and now I'm in the section about intialization of local variables. Here is what he said:

Nearly every local variable declaration should contain an initializer. If you don’t yet have enough in formation to initialize a variable sensibly, you should postpone the declaration until you do. One exception to this rule concerns try-catch statements.

So, what about the if-else statement? We need to initialize a variable only if some condition is satisfied, and intialize it in another way if it is not, like

MyClass mc = null;
if(cond)
   mc = new MyClass();
else
   mc = new MyClass(1);
//use mc

Since, it's not mentioned by J. Bloch, is it considered as a bad programming technique and should be avoided?

like image 274
St.Antario Avatar asked Feb 08 '23 19:02

St.Antario


1 Answers

In my opinion, the cleanest way should be:

final MyClass mc;
if (cond) {
   mc = new MyClass();
} else {
   mc = new MyClass(1);
}
//use mc

Because the final keyword will make sure, that the variable will always be initialized only once (for detailed explanation, look in your book at Item 15: Minimize mutability, page ~73).

And this is what you can't do in usual try-catch statements.

Also it's more effective and failsafe to always use curly braces.

like image 150
bobbel Avatar answered Feb 19 '23 03:02

bobbel