Search code examples
javaandroidif-statementmethodscode-duplication

Conditionally adding extra else if statements


The following is called from every level of my app (a game)

Pseudo code example

public void checkCollisions(){

    if (someCondition)
        do something

    else if (someCondition2)
        do something2

    else if (someCondition3)
        do something3

}

It's called like so:

mainGame.checkCollisions();

However, in selected levels, I need to throw in an additional condition, so instead of duplicating the whole method like..........

 public void checkCollisions2(){

    if (someCondition)
        do something

    else if (someCondition2)
        do something2

    else if (someCondition3)
        do something3

    else if (someCondition4)
        do something4

}

and then calling it like..........

mainGame.checkCollisions2();

I need to find a way to do this more efficiently (I'm sure there is one) The only way I can think of is taking in a boolean and then either carrying out the 4th condition (or not) depending on what the value of the boolean is, but that just doesn't seem a great way of doing it either (say, for example if I want to add even more conditions in the future).

This has to be an 'else if' statement so I can't just it into a separate method that I can call in addition to the original method.

Options would be appreciated


Solution

  • Have checkCollisions return a boolean that indicates whether it "did something".

    public boolean checkCollisions(){
        boolean didSomething = false;
        if (someCondition) {
           doSomething();
           didSomething = true;
        }
        else if (condition2) {
           doSomething2();
           didSomething = true;
        } 
        else if (condition3){
           doSomething3();
           didSomething = true;
        }
        return didSomething;
    }
    

    Then, checkCollisions2 can call checkCollisions and check if it did something. Then your else if can work normally:

    public void checkCollisions2(){
        if (checkCollisions()) {
           // Yes, something was done!
        }
        else if (condition4) {
           doSomething4();
        }
    }
    

    or shorter:

    public void checkCollisions2(){
        if (!checkCollisions() && condition4) {
           doSomething4();
        }
    }