Search code examples
javadesign-patternsbuilder

Business logic inside builder pattern


I have seen a programm which uses the builder design pattern.

To my understanding the builder pattern is used to create a whole object with different components. It's used to avoid long parameterlists which are not readable.

For example when i create a car object, I want to inside different types of an engine.

CarBuilder.addEngine(new dieselEngine).build();

How the car and the engine behaves is implemented in the car-class and the engine-class.

But now I have seen builder used to alter the logic of the object like:

CarBuilder.addEngine(new dieselEngine.addStartStopSystem().addCatalysis()).build();

You build very big builderS in which you are forced to use methods which alter the behaviour of this whole object you build. The builders get very large and I don't know which method to call when I want to have a certain behaviour by this object.

My opinion is that you shouldn't use any logic inside these builders. I would create an object which extends the main object and alter the behaviour there and hand it over in the builder.

What are your opinions? Should builders be used this way?

-----------------------UPDATE-------------------------

Maybe my example was poorly choosen. I will use a more abstract example In this builders I saw constructs like:

Object.output("First print output").Condition(is,String).onElse("Second print output").build();

So the builder determines in which way this "Object" should act. My problem there is that I can't get my head around which method to call on which other method and if this is the best way.

I haven't seen this pattern in another project implemented in this way.


Solution

  • I think it is messed with Fluent interface type. If you refer to the GOF builder pattern, you have provide concrete implementation for Builder interface where you have to write the logic. I assume that you may have to relooked into Fluent interface. I provide below few links for your reference. Fluent interface is best suited when you have telescopic pattern as mentioned in Effective Java.

    https://en.wikipedia.org/wiki/Fluent_interface

    https://en.wikipedia.org/wiki/Builder_pattern