Search code examples
javaseleniumif-statementdryrest-assured

How can I write this conditional if statement without duplicating function calls?


I'd like to refactor this Java/RestAssured code to remove the if statement altogether

if (someCondition) {    
    someRequestSpecification    
        .given()    
        .queryParam(THING, theThing)    
        .queryParam(SPECIAL_THING, anotherThing)    
        .get()
} else {    
    someRequestSpecification    
        .given()    
        .queryParam(THING, theThing)    
        .get()    
}

In other words I want to be able to omit the SPECIAL_THING param completely based on a condition but without having to duplicate the .given() code.

Currently I have the code working with the duplicated lines within an if statement but it's ugly.


Solution

  • You can refactor like this.

    RequestSpecification reSpec = given().queryParam(THING, theThing);
    if(condition){
        reSpec.queryParam(SPECIAL_THING, anotherThing);
    }
    reSpec.get();