Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best DRY if statement?

Let's say I want to compare a bunch of variables to one static variable, normally I would do it like this:

int w = 0;
int x = 1;
int y = 1;
int z = 2;
if(w == x || w == y || w == z){/*more code here*/}

But that can get extremely long and doesn't seem necessary, are there any ways to do something more like:

 if(w == (x || y || z)){/*more code here*/}

I would like to think that there is a way to do it like this.

like image 523
Zachrip Avatar asked Jul 01 '13 23:07

Zachrip


People also ask

How do you make an if statement more efficient?

Efficient if-else StatementsWhile in a serial if block, all the conditions are tested, in an if-else block the remaining tests are skipped altogether once an if expression evaluates to true. This approach is known as a circuit-breaker behavior and is way more efficient than a serial if block.

What is DRY in if?

The mnemonic DRY (Don't Repeat Yourself) vs. WET (Write Everything Twice) is a cute way to remember this.


2 Answers

Instead of:

if(w == x || w == y || w == z)

you can do:

if(Arrays.asList(x, y, z).contains(w))
like image 192
Adam Siemion Avatar answered Nov 02 '22 03:11

Adam Siemion


Though there is an answer accepted, I would want to share my ways too:

Method 1 is similar to the accepted answer. However, instead of using List, I use a Set. In such case, it may be even faster than doing == individually if there are lots of values to check against:

// make it a static final member if semantically possible
Set<Integer> ALL_VALUES = new HashSet<Integer>(Arrays.asList(a,b,c,d,e,f,g,h));

//.....

if (ALL_VALUES.contains(w)) {
  //... do something
}

Method 2 is to write a little utility function, something like

public static <T> boolean sameAsAny(T value, T... possibleValues) {
  for (T p : possibleValues) {
    if (value == p) {
      return true;
    }
  }
  return false;
}

with such util you can do something like:

if (sameAsAny(w, x, y, z)) 
like image 20
Adrian Shum Avatar answered Nov 02 '22 03:11

Adrian Shum