I am reading J. Bloch's efficient Java, and now I am in the section on initializing local variables. Here is what he said:
Almost every local variable declaration should contain an initializer. If you do not yet have enough formations to initialize the variable reasonably, you should defer the declaration until you do so. The only exception to this rule applies to try-catch statements.
So what about instructions if-else? We need to initialize the variable only if some condition is met, and initialize it differently if it is not, for example
if-else
MyClass mc = null; if(cond) mc = new MyClass(); else mc = new MyClass(1); //use mc
Since it is not mentioned by J. Bloch, is it considered a bad programming method 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
Since the last keyword will ensure that the variable will always be initialized only once (for a detailed explanation, look in your book at Point 15: Minimize Variability , page 73).
And this is what you cannot do in regular try-catch statements.
Moreover, it is more efficient and safer to always use curly braces .
You had to initialize the variable no matter what before using it.
, , .
int a; if (...) { a = 0; } else { a = 1;}
.
int a; if (...) { a = 0; }
, , 'a' .
'?' , :
MyClass mc = cond ? new MyClass() : new MyClass(1);
'mc' , ( if/else), . , . , , .
MyClass mc = null;
.. mc - if else. .
mc
if
else
if else, , , .
if-else, .
if-else, if-else.
Source: https://habr.com/ru/post/1611885/More articles:Obfuscation of the strings.xml file in Android code. - androidИсключение Null Pointer в Retrofit отклике - androidUsing locks in an asynchronous method - c #router.use TypeError: Unable to read the 'use' property from undefined - javascriptУскорение сравнения даты и времени с Cython - performanceJSON null field: blank quotes, null value or delete field? - javaHow to upload image file to alfresco using php - php"Hidden" toolbar is displayed in the status bar - androidgolang parse запрос POST - postThe element width is a fractional number in FF and IE, but the integer in Chrome is htmlAll Articles