I had to implement some code which traversed a small object hierarchy to fetch a value and display it in a TextView object (this is Android / Java). I had to do this 6 times to populate 6 TextViews for various values in the object hierarchy.
My implementation was Implementation B. But upon review, my colleague disagreed and certain that Implementation A was the way to go. I believe that my version is not just cleaner, but also less error prone as I could easily miss something as a developer.
Could you provide me with your opinion, with pros and cons for both of these implementations?
Implementation A:
if (house != null && house.getLounge() != null && house.getLounge().getLetter() != null)
{
String myValue = house.getLounge().getLetter();
textView.setText(myValue);
}
else
{
// Do nothing, or maybe make textView hidden.
}
Implementation B:
try
{
String myValue = house.getLounge().getLetter();
textView.setText(myValue);
}
catch (NullPointerException e)
{
// Do nothing, or maybe make textView hidden.
}
textView.*
access.this != null
? I'm no Java guru but I think the method invocation will throw before the method is entered iftextView
is null. In case you refer to other things that might be null insidesetText
, consider that those checks too can be buggy/incomplete.