Reputation: 481
I have an if-else structure in Java as follow:
if (A || B || C){
if (A){
//Do something
}
if (B){
//Do something
}
if (C){
//Do something
}
} else {
//Do something
}
I want to know if there is any cleaner and easier way to replace this?
Upvotes: 4
Views: 2327
Reputation: 2516
Just one more possible solution:
public class ABC {
private static final Logger log = LoggerFactory.getLogger(ABC.class);
@Test
public void abc() {
boolean A = true;
boolean B = false;
boolean C = true;
boolean abcProcessed = false;
abcProcessed |= process(A, () -> {
// Do something for A
log.debug("A");
});
abcProcessed |= process(B, () -> {
// Do something for B
log.debug("B");
});
abcProcessed |= process(C, () -> {
// Do something for B
log.debug("C");
});
if (!abcProcessed) {
// Do something for !(A||B||C)
log.debug("!(A||B||C)");
}
}
private boolean process(boolean flag, DoSomethingInterface doSomethingInterface) {
// check condition
if (flag) {
// execute code specific for condition
doSomethingInterface.doSomething();
// return true (processed)
return true;
}
// return false (not processed)
return false;
}
public interface DoSomethingInterface {
// code specific for condition
void doSomething();
}
}
An idea is to move condition checking and related code to separate method.
Upvotes: 1
Reputation: 100
I think you should use else if conditions:
if(A){
}else if(B){
}else if(C){
}else if(D){
}
But, if you have many conditions like A,B,C etc it feels that something wrong with logic of your program
Upvotes: 0
Reputation: 140514
Whilst I think what you have is fine, you could do it like this:
boolean d = false;
if (d |= A) { ... }
if (d |= B) { ... }
if (d |= C) { ... }
if (!d) {
// What to do if A..C are all false.
}
This will set d
to true if any of the conditions are matched (d
is for "did something").
Upvotes: 1
Reputation: 394086
If A,B and C are conditions which are expensive to evaluate, you could use an additional flag to make sure they are only evaluated once:
boolean found = false;
if (A) {
//Do something
found = true;
}
if (B){
//Do something
found = true;
}
if (C){
//Do something
found = true;
}
if (!found) {
//Do something
}
Otherwise (i.e. if they are not expensive to evaluate), I'd keep your current conditions.
Upvotes: 5
Reputation: 33563
Yes.
if (A) {
// do A
}
if (B) {
// do B
}
if (C) {
// do C
}
if (! (A || B || C)) {
// do "neither A or B or C"
}
Upvotes: 2