mariohez
mariohez

Reputation: 41

Change multiple if statements to avoid same code

I have the following code on a huge project. I want to find a better implementation to avoid the same code

if(CConst.CONST1.equals(SOMETHING1)){
    const1fieldsaver = true;
    if(a != 0){
        //same code
        if(value <= 0){
            const1field = ...//same code
    }
}

if(CConst.CONST2.equals(SOMETHING2)){
    const2fieldsaver = true;
    if(a != 0){
        //same code
        if(value <= 0){
            const2field = ...//same code
    }
}

how can i avoid these to if statements? The have the same code but as you can see it save the values to different variables. Is there any more efficient way to implement this?

Upvotes: 0

Views: 64

Answers (2)

user15314575
user15314575

Reputation:

If possible, assign conditions directly to booleans and merge If-Statements.

e.g.

const1fieldsaver = CConst.CONST1.equals(SOMETHING1);
if(const1fieldsaver && a != 0 && value <= 0) {
    const1field = ...
}

For more complex conditions I would use functions as recommended by Ted Lyngmo.

Upvotes: 0

TheSj
TheSj

Reputation: 386

I would suggest creating a method that you call inside each if block that executes the code you want.

if(CConst.CONST1.equals(SOMETHING1)){
    const1fieldsaver = true;
    if(a != 0){
        executeSameCode(); //calling method here
        if(value <= 0){
            const1field = ...executeSameCode2(); //calling method, note that it is different from above method. 
    }
}

if(CConst.CONST2.equals(SOMETHING2)){
    const2fieldsaver = true;
    if(a != 0){
        executeSameCode();
        if(value <= 0){
            const2field = ...executeSameCode2();
    }
}


//somewhere else inside the class

public void executeMethod() {
     //your code 
} //can be made to return stuff

public void executeMethod2() {
     //your code
} //again, can be made to return stuff

This way, you don't need to set up lots of temporary variables, but instead, just call the method from wherever you want.

Hope that helped!

Upvotes: 1

Related Questions