I\'m wondering if I\'m missing something about Java Beans. I like my objects to do as much initialization in the constructor as possible and have a minimum number of mutators. B
I like my objects to do as much initialization in the constructor as possible and have a minimum number of mutators.
Favouring immutable objects is a wise choice. However the benefit of beans is that frameworks/tools/libraries can determine at runtime the properties of a class, without requiring you to implement a particular interface.
For example, assume you have a collection of Person beans, and each bean has properties such as name, age, height, etc.
You can sort this collection of beans by name (for example) using the following code:
Collection myCollection = // initialise and populate the collection
Comparator nameCompare = new BeanComparator("name");
Collections.sort(myCollection, nameCompare);
The BeanComparator class knows how to extract the "name" property from each object, because the Java Beans convention is followed, i.e. you're spared the "overhead" of implementing an interface such as:
interface Nameable {
public String getName();
public void setName(String name);
}
Another example from Spring MVC is a bean that stores request URL parameters. This can be defined in a web controller (known as an 'Action' in Struts) like this:
public ModelAndView searchUsers(UserSearchCriteria criteria) {
// implementation omitted
}
Because UserSearchCriteria is expected to be a JavaBean, if the request URL contains a parameter such as maxItems=6
, the Spring framework 'knows' that it should call a method with the signature
void setMaxItems(int maxItems);
In essence, JavaBeans is just a simple convention which allows the properties of a class to be discovered dynamically at runtime (usually by a tool or framework), when it's inconvenient/impossible to know a priori the properties that may be provided.