Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logic inside BuilderPattern

Recently I came across with a builder pattern that intrigued me.

So, I have an EntityBuilder which builds an Entity, but it doesn't return the entity. Here is the method signature:

public void build();

Instead, inside the build() method, it delivers the new object created, the Entity, to a CacheImplementation instance to store it. Note: the CacheImpl is injected in the builder's constructor.

public void build(){
    //create new entity
    cacheImplementation.add(entity);
}

Does this sounds like best practice?

Later edit 0

public interface EntityBuilder {

    void setProperty0(PropertyObject propertyObject0);
    void setProperty1(PropertyObject propertyObject1);
    void setProperty2(PropertyObject propertyObject2);
    //...

    void build();
}

public class EntityBuilderImpl implements EntityBuilder {
    
    PropertyObject propertyObject0;
    PropertyObject propertyObject1;
    PropertyObject propertyObject2;
    //...

    // setters for all properties
    @Override
    public void build(){
        //create new entity
        cacheImplementation.add(entity);
    }
}

The builder is used in the following way:

public class EntityProcessor{
  private EntityBuilderFactory entityBuilderFactory;//initialized in constructor

  void process(EntityDetails entityDetails){
       EntityBuilder entityBuilder = this.entityBuilderFactory.getNewEntitytBuilder();
       //..
       // entityBuilder.set all properties from entityDetails
       entityBuilder.build();
  }
}

Note: the cacheImpl instance just stores the entities in a List<> which is accesses every N seconds.

like image 778
VladLucian Avatar asked Oct 02 '15 15:10

VladLucian


1 Answers

Does this sounds like best practice?

The traditional builder pattern doesn't store the created object anywhere, it simply returns it.

I can imagine a variation where the builder also has a role of instance control to avoid creating duplicate objects, and managing a store of immutable objects.

The decision to not return an instance could be to make it clear that the method has a side effect. If the method returned the object, it might mislead to thinking that it's a traditional builder without side effects, when that's not the case here.

In any case, all this is just speculation, as we haven't seen the rest of the code where this is used and the way it is implemented and used. We don't have enough context to really judge. There's nothing wrong with inventing new patterns, but it can be done well or badly.

like image 116
janos Avatar answered Nov 09 '22 18:11

janos