Skip to main content

2 Builders, 1 Code? WithCRTP()

· One min read
Daniel Maß
Maintainer of Xcepto

Did you ever copy-paste builder methods across similar builders and just accept it?

This is especially painful when creating multi-stage fluent APIs — ones that only expose valid methods at each build step.

CRTP (Curiously Recurring Template Pattern) eliminates this entirely. It lets base classes return the concrete builder type instead of the abstract one.

Where this helped

I benefitted greatly from this while creating fluent APIs for Xcepto, my declarative testing framework.

Both the RestAdapter and the SsrAdapter builders require generic HTTP building methods like WithHTTPVerb(verb) and AddQueryParameter(key, value).

Without CRTP I would have had to implement them twice, violating the Single-Source-Of-Truth principle and making the implementation prone to inconsistent changes.

Instead I moved them into an abstract HTTP builder base.

One source of truth. No duplication.

This is how Xcepto's builders stay consistent across adapters without duplicating a single method.


Originally published on themassiveone.net.