user1692342
user1692342

Reputation: 5237

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

Upvotes: 1

Views: 1154

Answers (1)

Kevin Krumwiede
Kevin Krumwiede

Reputation: 10308

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.

Upvotes: 3

Related Questions