To avoid duplication in the code, is there a way to extract to a separate method of the selected code?
class Builder
{
private final List< UnitIf > unit = new ArrayList<>();
private final List< TimeIf > time = new ArrayList<>();
public Builder withUnit( final UnitIf aUnit )
{
//Extract to method
if( aUnit != null )
{
unit.add( aUnit );
}
return this;
//----------------
}
public Builder withTime( final TimeIf aTime )
{
//Extract to method
if( aTime != null )
{
time.add( aTime );
}
return this;
//----------------
}
}
My goal is to simplify the code by eliminating duplication. But the parts of code use different data types.
Add a method
public <T> Builder addIfNonNull(List<T> dst, T x)
{
if (x != null) {
dst.add(x);
}
return this;
}
and implement withUnit
like
public Builder withUnit( final UnitIf aUnit )
{
return addIfNonNull(unit, aUnit);
}
and change withTime
the same way.
If you don't want it to be a generic method, just omit the type parameter T
and change the type of x
to be Object
:
public Builder addIfNonNull(List dst, Object x)
{
if (x != null) {
dst.add(x);
}
return this;
}
Internally, the Java compiler will compile List<T>
to just List
. I think it is called "type erasure".