Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating nested fluent API in Java

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:

Attribute Builder

AttributeBuilder.make().name().value().build();

Item Builder

ItemBuilder.make().action()
                   .attribute()
                               .name().value().build()
                   .attribute()
                               .name().value().build()
                    .build();

Order Builder

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 ?

like image 452
user4692694 Avatar asked Aug 03 '26 12:08

user4692694


1 Answers

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.

like image 53
iluwatar Avatar answered Aug 06 '26 02:08

iluwatar