What is the “right” way to do this (if statement)

I have a lot of these lying, and I wonder if I run into any problems or performance issues.

I have method A:

MyClass monkey; ... if(monkey != null) { ... } 

Or method B:

 boolean hasMonkey; //This is set to TRUE when monkey is not null MyClass monkey; ... if(hasMonkey) { ... } 

At the functional level, they both do the same thing. Right now, I'm using method A. Is this a bad way to do something? What will be better?

+6
java android
source share
8 answers

Method A is what I saw as a “general” case. Method B introduces the problem of data consistency (that hasMonkey not installed correctly?), Whereas Method A relies only on the object itself to determine its validity. In my opinion, Method A is far superior.

+19
source share

Method A is OK - why clutter the code with unnecessary variables?

+3
source share

Method A simply matters more because it stores data in one place, so you don't have to worry about updating hasMonkey everywhere.

+3
source share

There is nothing wrong with method A, IMO. Method B is a kind of violation of the DRY principle (as I see) - setting and checking a flag indicating whether the monkey link is null, duplication / backup.

I do not think there are any performance implications for any of these approaches, since you are testing the condition in both cases.

+3
source share

I would say using the first method.

The problem with the second method is that you have redundant information. Perhaps you can get a situation where you have a monkey , but hasMonkey is false or perhaps worse: according to hasMonkey you have a monkey, but when you try to access a member, it throws a NullPointerException . The first method avoids this potential problem.

+2
source share

Definitely method A. If you want to test monkey against null , just do it. Why do you include an additional variable? Who makes sure to always set it appropriately? More headaches, more error prone, no gain.

+2
source share

In general, I would choose A - more understandable, simple and consistent.

But if it is in a tight loop, you can try a second, but always profile. Whether there is a performance gain depends on how smart the virtual machine is. Depending on the implementation of the virtual machine, you may have to check the null pointer before using the monkey link if the underlying hardware cannot be used to trap invalid pointer access. In this case, the virtual machine will always check the link, but it can also be smart enough to find out if the link is not null. if you have an explicit check. Thus, using A may still be the most efficient option.

+1
source share

Method A is certainly better, since you do not need to spend additional overhead on another logical value that will require additional memory space on the stack and, according to your description, should be supported up to the volume of the Monkey object.

0
source share

All Articles