Reputation: 27385
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?
Upvotes: 4
Views: 135
Reputation: 3356
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.
Upvotes: 4
Reputation: 415
You had to initialize a variable no matter what before it can be used.
If compiler analysis detects that a variable is initialized before it may be used, you can define a variable without initialization.
For example
int a;
if (...) { a = 0; }
else { a = 1;}
would be fine. However
int a;
if (...) { a = 0; }
would result in a compiler error as the condition may not become true in which case 'a' remains uninitialized.
Personally I prefer the '?' operator for cases as shown in your code:
MyClass mc = cond ? new MyClass() : new MyClass(1);
If you need the reference 'mc' outside the scope where it is initialized (the if / else block) you have to do it that way. It do not know this being considered bad practice. However in your concrete case a better solution might be possible but that is difficult to say without knowing the whole code.
Upvotes: 2
Reputation: 13402
MyClass mc = null;
This is sort of redundant. Because the variable mc
any way going to initialize either in if
or else
clause. so you can avoid it.
If you were initializing two different objects in if
and else
part, then you should initialize it while declaring, so you know what to expect from a particular variable later in your program.
Upvotes: 1
Reputation: 4614
If the use of variable is outside the if-else
block your declaration is fine.
But in case you want to use the variable within if-else
block you should declare and use it within the if-else
block.
Scope of use should decide initialization and declaration of variable.
Upvotes: 1