Best DRY if expression?

Let's say I want to compare a bunch of variables with one static variable, usually 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 this can become very long and does not seem necessary, are there any ways to do something more:

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

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

+4
source share
4 answers

Instead:

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

You can do:

 if(Arrays.asList(x, y, z).contains(w)) 
+9
source

Although there is an accepted answer, I also want to share my ways:

Method 1 is similar to the accepted answer. However, instead of using List, I use Set. In this case, it can be even faster than doing == individually if there are many values ​​to check:

 // 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 small useful function, something like

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

with this use you can do something like:

 if (sameAsAny(w, x, y, z)) 
+3
source

You can format it as follows:

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

I find this helps break down conditions and make reading easier.

0
source

In Java, this is not allowed. But you can learn some rules based on engines, such as drools .

0
source

Source: https://habr.com/ru/post/1489181/


All Articles