views:

46

answers:

3

Example:

That code is run each time, when the listAdapter requests a new row:

if (textViewTitle != null)
          textViewTitle.setTypeface(Controller.getInstance().widgetSettings.getBoldTypeface());

vs.

if (textViewTitle != null 
    && textViewTitle.getTypeface() != null
    && textViewTitle.getTypeface().equals(Controller.getInstance().widgetSettings.getBoldTypeface()))
          textViewTitle.setTypeface(Controller.getInstance().widgetSettings.getBoldTypeface());
+2  A: 

Make sure textViewTitle always refers to something so you don't need to check for its existence.

Lie Ryan
With "textViewTitle != null" I'm making sure that it refers to smth. (I have different types of row views in my list)
OneWorld
@OneWorld: No, you are making excessive wasted checks. Your constructor should initialize the object and fill textViewTitle with something, so you can be sure that textViewTitle is never null after the constructor is finished. Alternatively, you can use "Null Object Pattern" http://en.wikipedia.org/wiki/Null_Object_pattern
Lie Ryan
@OneWorld: I recommend reading about "Design By Contract" http://en.wikipedia.org/wiki/Design_by_contract ; in DbC, the class constructor should initialize the instance, and all public methods should enforce the class invariant so that textViewTitle should never contain `null`. If it's never null, then you can always call .getTypeFace, .setTypeFace safely.
Lie Ryan
+3  A: 

It depends entirely on how costly the creation and equality operation are. It should be trivial to benchmark as needed if performance is that important.

If performance isn't so important, then the former is far more readable, and conveys just as much information about the intention of the code as the latter.

Andy
A: 

Maybe setTypeface is more than just setting a property, for example causes redrawing? In this case you would like to avoid calling it unless it changes something.
BTW in second code if original typeface is not set, it won't be set. I'm not sure if it's intended.

Tadeusz Kopec