dagblog.
← Archive

Taking inspiration from dynamic languages


For a long time I looked down on dynamic languages like Groovy and Ruby. That may be a strong way to put it, but over time I’ve come to find some of their features quite wonderful. Part of their popularity surely comes from how readable the resulting code is. You could put that down to syntax, which would be hard to change in Java, but syntax is only part of it. These languages more often use an approach to API design known as a fluent interface.

Martin Fowler illustrates the difference between a conventional API and a fluent one in this example.

private void makeNormal(Customer customer) {

 Order o1 = new Order();

 customer.addOrder(o1);

 OrderLine line1 = new OrderLine(6, Product.find("TAL"));

 o1.addLine(line1);

 OrderLine line2 = new OrderLine(5, Product.find("HPK"));

 o1.addLine(line2);

 OrderLine line3 = new OrderLine(3, Product.find("LGV"));

 o1.addLine(line3);

 line2.setSkippable(true);

 o1.setRush(true);

 }

private void makeFluent(Customer customer) {

 customer.newOrder()

 .with(6, "TAL")

 .with(5, "HPK").skippable()

 .with(3, "LGV")

 .priorityRush();

 }

What I like is that the context never has to be repeated. It comes from the way the code flows. There’s very little clutter. This, I think, is what “self-documenting code” means. As Fowler points out, it does break some familiar idioms, such as the setter that returns nothing.

You can build APIs this way without a dynamic language. With a bit of care and the right pattern (Method Chaining), you can do it in Java too.

I see a fluent interface as a way to think about API design so that the API makes sense and is easy to read when you use it or look at how someone else used it. It won’t be right everywhere, but it’s worth considering at least for an application’s domain model.

Medium version

Related articles

Related CZ Podcast episodes