Fluent APIs and types
I'd like to borrow an example from Mario Fusco to illustrate how to take advantage of types to make programming safer and more fun. Consider this Java class:
The class uses the return this trick to enable method call chaining. However, there is a temporal dependency between the methods in this class, and if I call them out of order, I will get an exception at runtime. At runtime, possibly throwing an exception in the face of a user!
The nice thing is that we can use types to prevent this error at programming time. That is:
Now if you start with a HungryCat, the only option you have is to call method catchBird(...) , and the IDE itself will guide you towards invoking the correct method:
And this is how you do a fluent API: at every step, the IDE guides us to choose among the available methods, and the compiler prevents us to invoke methods out of order.
The original example from Mario Fusco is just 2 slides out of this slideshare presentation, that contains a lot of other good stuff.
Passionate Programmer, AI Expert, Hands-on Architect, Public Speaker, Author, Android-Kotlin GDE
1 年It's easier if you use a sealed interface Cat (or CatState) to be sure to get all possible kind of cats. Also you can map the different state changes in an CatEvent class... and you know where this will end. :)
Senior Software Engineer
1 年Thanks Matteo for the article. In the latests months I've been using Rust and this article made me immediately think to the typestate pattern. It's a very convenient way, available in Rust, to do the exact same thing you did. The difference is that the "state" goes in the type parameter. Something like this..
Technical Coach / Divulgatore Informatico / Founder @Mirai Training @DevDojoIT
1 年Very nice point of view, thanks for sharing
Senior Software Engineer | Tech enthusiast
1 年I love this example, thanks Matteo ??
Consulting, Coaching & Training for Modern Software Engineering - Innovative Agile Software Technical Training Coach & Trainer| Co-Autor “Agile Technical Practices Distilled” Award Winning Book | Co-founder Alcor Academy
1 年Very nice! This is an example of Connascence of Execution Order. Another way to solve it, without breaking the Cat in different classes, could be leveraging Interface Segregation. The Cat would implement all the interfaces, but using a Factory Method you can expose it as the interface with the right behaviour in the right time!