I like the approach of customizing behavior through builder methods that return immutable instances. Here's how Guava Splitter uses it:
private static final Splitter MY_SPLITTER = Splitter.on(',')
.trimResults()
.omitEmptyStrings();
MY_SPLITTER.split("one,,,, two,three");
private static final Splitter MY_SPLITTER = Splitter.on(',')
.trimResults()
.omitEmptyStrings();
MY_SPLITTER.split("one,,,, two,three");
The benefits of this are:
- Superior readibility
- Clear separation of configuration vs. action methods
- Promotes cohesion by forcing you to think about what the object is, what it should and shouldn't do. In this case it's a
Splitter. You'd never putsomeVaguelyStringRelatedOperation(List<Entity> myEntities)in a class calledSplitter, but you'd think about putting it as a static method in aStringUtilsclass. - The instances are pre-configured therefore readily dependency-injectable. The client doesn't need to worry about whether to pass
trueorfalseto a method to get the correct behavior.