Details
-
New Feature
-
Status: Open
-
Major
-
Resolution: Unresolved
-
None
-
None
Description
The attached patch allows users to easily define what I'm calling a "fluid" bean (though there might be a better name for it).
The idea here is to write a bean that doesn't follow the standard JavaBean convention. Specifically, a "fluid" bean's setters return "this," so you can "chain" calls to the setters, and the getters and setters don't start with "get/set" but are just the name of the property. For example:
public class Employee extends AbstractFluidBean { private String firstName, lastName; public String firstName() { return firstName; } public Employee firstName(String firstName) { this.firstName = firstName; return this; } public String lastName() { return lastName; } public Employee lastName(String lastName) { this.lastName = lastName; return this; } }
Fluid beans have some limitations: you can't use indexed or mapped properties with a fluid bean (because there's no way to disambiguate an indexed getter from a simple setter). I think that's OK because indexed properties are a bit silly. (Why not just return a List or a Map?)
But I think they have substantial readability advantages. With a fluid bean, you can write code like this:
HumanResources.hire(new Employee().firstName("Dan").lastName("Fabulich"));
For an example of fluid chained setters in the wild, see (for example) Effective Java Second Edition by Joshua Bloch. In Item 2 "Consider a builder when faced with many constructor parameters" Bloch defines a fluid bean with chained setters, so you can use it like this:
NutritionFacts cocoCola = new NutritionFacts.Builder(240, 8)
.calories(100).sodium(35).carbohydrate(27).build();