For situations where you can't use a switch but you still have some complicated condition to evaluate you can use an "explanatory variable"
// before
if ( a && b || c != d && e > f && g < h && h == 1 ) {
doSomething();
} else if ( i && j || etc ) {
doSomethingElse();
}
//after with a variable
boolean shouldDoSomething = a && b || c != d && e > f && g < h && h == 1;
if ( shuoldDoSomething ) {
doSomething();
} else if ( i && j || etc ) {
doSomethingElse();
}
Or create a method that evaluates the condition:
// after with a method
if ( shouldDoSomething(a,b,c,d,e,f,g,h) ) {
doSomething();
} else if ( shouldDoSomethingElse(i, j, etc )) {
doSomethingElse();
}
...
private boolean shouldDoSomething( boolean a,boolean b,int c,int d,int e,int f,int g,int h) {
return a && b || c != d && e > f && g < h && h == 1;
}
private boolean shouldSoSomethingElse(boolean i, boolean j, boolean etc ) {
return i && j || etc;
}
The objective is to simplify your code allowing you to understand it better and making it easier to modify a less error prone. If using a variable or creating a method is more confusing then continue with the simple evaluation. You can also combine the three:
//
boolean shouldDoX = a || b;
if ( shouldDoX || e != d && inRange(f, g, h ) ) {
doSomething();
}
Again the objective is to make it easier to maintain.
In this example the variables are a, b, c but in real code you should use a short meaningful variable name
if ( inRange(random) ) {
label_number.setForeground(SWTResourceManager.getColor(SWT.COLOR_BLUE));
} else if ( outOfRange(random)) {
label_wheelNumber.setForeground(SWTResourceManager.getColor(SWT.COLOR_GREEN));
}
...
private boolean inRange(int random ) {
// use switch or simple return random == 1 || random == 2 etc.
}
Also, final notes on style: do always use brace on your if's even if they are one line and keep the opening brace in the same line. In Java, variables start with lowercase and are written in camelStyle ( no underscores ). These are just style conventions and will help you to create good habits. Each language has its own conventions, learn them and use them.