0

Which of these two is the better way of doing the same thing -

public void someMethod(String s, boolean bool02){
 boolean bool01 = s!=null;
 if(bool01==bool02){
  doSomething();
 }
}

OR

public void someMethod(String s, boolean bool02){
 List<String> list=new ArrayList<String>();
 if(s!=null && bool02){
  doSomething();
 }
}

The way I understand it is, Option 1 -

  1. Computes s!=null
  2. Set it to bool01
  3. Compares bool01 to bool02

and Option 2 -

  1. Computes s!=null
  2. Compares it with true
  3. Compares bool02 to true(depending if step 2 was true)

This is not a big deal but its bugging me to know which one is better. Or does the compiler optimization(if any) converts both of them to the same thing?

1 Answers1

11

They are both horrible.

The better one is the one that actually does what it's supposed to do. These don't do the same thing.

s!=null is bool01  |  bool02  |  bool01==bool02  |  s!=null && bool02
        F          |    F     |        T         |          F
        F          |    T     |        F         |          F
        T          |    F     |        F         |          F
        T          |    T     |        T         |          T

Which one does what it's supposed to do is impossible to say because you've removed any hint of what's going on with meaningless names like someMethod(), doSomething() and, my good god, bool01. This is the biggest problem.

public void printLength(String s, boolean allowException) {
    if (s != null || allowException) {
        System.out.println( "String length : " + s.length() );
    }
}

There, now it means something. I can look at it without my head hurting.

For future reference the logical equivalent of == isn't &&. It's NOT XOR

       ^  !^ == &&
F  F   F  T  T  F
F  T   T  F  F  F
T  F   T  F  F  F
T  T   F  T  T  T

Now sure, I could make printLength() occasionally slightly faster by putting allowException first in the OR and use short circuit evaluation to avoid the subtraction required to compare the s reference to null. I don't care. Not because this is only a tiny savings, but because I think it's more readable to see the null check first before thinking about allowing the exception.

The only performance anyone should care about here is how this performs in your head.

candied_orange
  • 119,268