Just to ensure there is a fully balanced set of answers to this question I would like to post a different opinion.
I think this mechanism is foolish.
If you have a null
you should know as soon as it happens - hiding it will just postpone its discovery. If the null
is not an exception, replace it with something else.
Taking this approach will fortify your code with what is called defensive programming where your mistakes are discovered as soon as possible rather than covered up until everything falls apart.
In summary - NullPointerException
is your friend. You should use it to find mistakes in your code. It is very easy to use a Empty object such as Collections.emptySet()
once you have determined that the null
is not an exception.
Using the Yoda technique out of habit will inevitably hide errors you do not mean to hide. Not using it will expose errors much earlier. To me that is sufficient argument to not use it - ever.
To me - using
if(saving != null && saving.equals("true")){
means that I actually want to allow savings
to be null
and it is an acceptable situation - using
if("true".equals(saving)){
merely hides that deliberate choice in a way that could become a bad habit.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…