简体   繁体   中英

Splitting the Java builder to avoid writing same code multiple times

I have a piece of code which looks like below:

Problem hashProblem;
String indexName;
if(condition.getOwner() != null) {
    indexName = sourceLocation ;
    hashProblem = new Problem().builder()
        .locationID(condition.getLocationID())
        .sourceLocation(condition.getSourceLocation())
        .build();
}
else {
    indexName = currentLocation;
    hashProblem = new Problem().builder()
        .locationID(condition.getLocationID())
        .currentLocation(criteria.getcurrentLocation())
        .build();
}

Is there a way to write this code in a more elegant way? While building the hashProblem object setting the locationID is always required. I am unable to think of a way to split the builder so that I could write .locationID only once. I am using Lombok( https://projectlombok.org/features/Builder.html ) for builder

Sure. A builder is an object just like any other. Instead of creating the builder and calling build() in one big statement, you can save a reference to the builder, do something to it conditionally, and then call build() .

Problem hashProblem;
String indexName;
Builder builder = new Problem().builder().locationID(condition.getLocationID());
if(condition.getOwner() != null) {
    indexName = sourceLocation ;
    builder.sourceLocation(condition.getSourceLocation())
}
else {
    indexName = currentLocation;
    builder.currentLocation(criteria.getcurrentLocation())
}
hashProblem = builder.build();

By the way, new Problem().builder() looks a bit strange in terms of naming conventions. Typically you would see new Problem.Builder() , where Builder is a nested class of Problem , or Problem.builder() (no new ) where builder() is a static method that returns a Problem.Builder .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM