tags:

views:

280

answers:

8
+18  A: 

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.

VeeArr
Thanks, that's what I wanted to hear :)
Sticky
For clarity, you could have a method `boolean hasMonkey()` that returns `monkey != null` as well.
ColinD
+3  A: 

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

Otávio Décio
+2  A: 

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.

Mark Byers
+2  A: 

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.

tzaman
+3  A: 

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.

CheesePls
+3  A: 

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.

ssahmed555
+1  A: 

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.

mdma
A: 

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.

Chinjoo