3 ms·
As a fan of immutable objects, I bemoan the builder pattern. The nice thing about constructors (or factory methods) is that you have a compile time guarantee th
by jonhohle 11y ago
As a fan of immutable objects, I bemoan the builder pattern. The nice thing about constructors (or factory methods) is that you have a compile time guarantee that you have all required components to construct an object and validate its invariants. With a field oriented builder, only the documentation informs you whether you've met all of the conditions to construct an object. Also, a builder which mutates its own internal state breaks the idea of partial application where several variants can be constructed from a parent.
Unrelated to builders, the stream example could be simplified further with method references
final List<String> filtered = list.stream()
.filter(s -> s.startsWith("s"))
.map(String::toUpperCase)
.collect(Collectors.toList());
It would be nice if Oracle back filled some predicates to make them more useful in streams (e.g. "s"::isPrefixOf, etc.).
- benjiweber 11y agoYou can create immutable "builder" with lambda chains. This also gives you the compiletime guarantee that you have specified the required fields (At the cost of flexibility and ease of adding new fields) http://benjiweber.co.uk/blog/2014/11/02/builder-pattern-with-java-8-lambdas/ http://benjiweber.co.uk/blog/2014/11/02/builder-pattern-with... Regarding your isPrefixOf - is there a significant benefit to that being in the standard library? You could define a isPrefixedWith("s") that returns a Predicate<String> yourself.
- hepta 11y agoThis is great, thanks. I've also used something like this: https://gist.github.com/dwijnand/3741951 https://gist.github.com/dwijnand/3741951
- jacques_chester 11y agoThe Builder pattern includes setting sensible defaults on the built object before building it. You configure the built object in the constructor of the Builder, before anyone starts updating fields. You can achieve this through constructors or setters; Builder itself is agnostic.