2 ms·
Just 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
by Izkata 3y ago
Just 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.