HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Splitting the Java builder to avoid writing same code multiple times

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
samethebuilderwritingsplittingjavaavoidmultiplecodetimes

Problem

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.

Solution

The builder instance can be extracted into a dedicated reference and you'll be able to apply the common instructions on it only once, for example:

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

Code Snippets

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

Context

StackExchange Code Review Q#158105, answer score: 8

Revisions (0)

No revisions yet.