We are trying to come up with fluent API for nested Object. Consider we have following three classes
Attribute : name : String Value : Object
Item : action : String attributes :
Order : action : String attributes : items :
Here we want to have fluent API which can help to build above Objects.
Now we need to have builders as follows:
AttributeBuilder.make().name().value().build();
ItemBuilder.make().action()
.attribute()
.name().value().build()
.attribute()
.name().value().build()
.build();
OrderBuilder.make().action()
.attribute()
.name().value().build()
.attribute()
.name().value().build()
.item()
.action()
.attribute()
.name().value().build()
.attribute()
.name().value().build()
.build()
.build();
We may later nest the Order Object in Some other object.
So is there any way to achieve such nested DSL building ?
Wow, that's a lot of Builders. Are you sure you need to build each and every detail of the hierarchy like this?
Looking at the code we can see that the entities form a tree-like hierarchy. Orders have items and items have attributes. If the entities are really going to be this simple you could construct the hierarchy without using Builders at all. See for an example here.
For fluent handling of the orders you could employ the Composite pattern. For example, if you would need to calculate the price of the order based on the items and attributes. Or subtract the ordered items and attributes from the storehouse saldo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With