开发者

Which is the 'correct' way to do this (if statement)

I've got plenty of these lying around, and I'm wondering if I'm going to face any trouble - or performance problems.

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 monke开发者_Python百科y;
...
if(hasMonkey) {
 ...
}

On a functional level, they both do the same thing. Right now, I'm using method A. Is that a bad way of doing things? Which is going to perform better?


Method A is what I have seen as the "common" case. Method B introduces a problem of data consistency (what is hasMonkey does not get set correctly?), while Method A relies on only the object itself to determine its validity. In my opinion, Method A is far superior.


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


Method A simply makes more sense since it keeps the data in one place so you don't have to worry about updating hasMonkey everywhere.


There's nothing wrong with method A, IMO. Method B is sort of a violation of the DRY principle (as I see it) - setting and checking a flag to indicate whether or not the monkey reference is null is a duplication/redundancy.

I don't think there are any performance implications with either approach since you're testing a condition in both cases.


Definitely method A. If you want to test monkey against null, just do that. Why would you involve an extra variable? Who keeps track of always setting it appropriately? More headache, more error-prone, no gain.


I would say use the first method.

The problem with the second method is that you have redundant information. It's possible that 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.


In general, I would choose A - clearer, simpler, and consistent.

But, if this is in a tight loop, then you might try the second one, but always profile. Whether there is a performance gain depends upon how smart the VM is. Depending on the implementation, the VM may have to check for a null pointer before using the "monkey" reference if the underlying hardware can't be used to trap an invalid pointer access. In that case, the VM will always check the reference, but it may also be smart enough to figure out if the reference is not null - e.g. if you have an explicit check. So, using A might still be the most performant option too.


Method A is certainly better as you dont have to go for an extra overhead of another boolean value which will require extra memory space in stack and as per your description, has to be kept alive till the scope of Monkey object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜