2 ms·
The builder pattern [0] is orthogonal to fluent interfaces. It has merely become customary for builders to have a fluent interface. The defining feature of the
by layer8 3y ago
The builder pattern [0] is orthogonal to fluent interfaces. It has merely become customary for builders to have a fluent interface. The defining feature of the builder pattern is that you don’t set configurable properties on an object itself, but that you use a separate object (the builder) to set the properties on, and then have it build the final object (on which the respective properties are then usually immutable). It’s immaterial whether the builder object has a fluent interface or not. The important thing is that the builder interface is separated from the resulting object’s interface.
[0] https://en.wikipedia.org/wiki/Builder_pattern https://en.wikipedia.org/wiki/Builder_pattern
Both builders and fluent interfaces have little to do with point-free style. X.foo().bar().baz() is not any more point-free than baz(bar(foo(x))).
- Izkata 3y agoJust to add a bit of clarity: GP's second example isn't a builder pattern, because it's missing the actual build step. Builder patterns use method chaining to configure an object, but the final result is an object of a different class, something that doesn't have those initial methods but instead lets you use the result of what was built up. Java's StringBuilder is a classic example, which exists to avoid the O(n^2) of concat'ing multiple values sequentially, after which you use .toString() to return the actual String object built up. GP's first example is one where the builder pattern lets you name constructor arguments, and during the final build it would throw an exception if you have an incompatible combination. Whether GP's second example counts as a fluent interface is a bit iffy just because of SQL keywords and how it works in general, but possibly a good way to think of fluent interfaces is madlibs: "Find a ___(noun) that is ___(adjective)". Instead of creating a function with complicated arguments like "find(noun, adjective)" or "find(Noun(n, adjective))", you'd mimic the sentence structure with something along the lines of "collection.find(noun).thatIs(adjective)" - the chained methods interact with each other to flexibly specify complicated arguments. The ".thatIs()" could for example be completely omitted or specified multiple times to further restrict what "noun" to return. The query builder is iffy because while it looks like one on the surface, it's actually plain method chaining where each call modifies and returns the original object without the context that's passed to the next call in a fluent interface. Method chaining is the simple syntactic pattern that enables both of these other patterns. An umbrella term they both fall under.