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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With