Home > Back-end >  Refactoring. How extract code to a generic method?
Refactoring. How extract code to a generic method?

Time:11-26

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.

CodePudding user response:

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.

  • Related