1
\$\begingroup\$

This upvoted SO answer and this upvoted SO answer both check for null in a similar way: they call a function in the if or assert statement and "throw away" the result and then call the same method again in the success clause and operate on the result.

I am new to Android development and have limited knowledge of Java, but my experience in other languages (and every bone in my body) tells me it would be better to store the result of the function in a local variable, test that in the if statement and then use that local variable value in the success clause like this:

ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
    actionBar.setDisplayHomeAsUpEnabled(true);
}

Am I missing something (because the answers on SO are upvoted and no-one has suggested this alternative); is my suggestion above flawed in Java?

\$\endgroup\$
1
\$\begingroup\$

Assuming java conventions are being followed, methods that begin with get should return an already-computed value with no business logic performed. In that case, the only real 'cost' tradeoff is the overhead of a second method call vs. the memory for new pointer to the value. Both should be insignificant. It's generally a matter of style as to which approach is preferable.

\$\endgroup\$
  • \$\begingroup\$ Thanks for sharing your knowledge on this. I can embrace coding by convention but coding by assumption might be a step to far for me; it's nice to know my code is acceptable. Thanks again. \$\endgroup\$ – lukkea Oct 22 '15 at 8:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.