Java Reference
In-Depth Information
Tim Says. . .
Using Public Fields with Stripes Is Not a Bad Thing
Stripes can access action bean properties in two different ways. The
most common way is through getter and setter methods, but Stripes
will also work directly with public fields. These two ways are completely
equivalent to Stripes. Using a public field is more compact—you don't
need to write boilerplate getter and setter methods for each property.
So, why wouldn't you use public fields?
Other than for constants, using public fields in Java has been looked
down upon for a long time. The reason is encapsulation. Forcing client
code to use methods to get and set properties allows you to change
how the property is stored and retrieved without impacting client code.
When a public field is used, you have to change all client code to use
the getter method. Another benefit of using methods is that it allows
you to do extra things when the value is read or set (increment a
counter, log a message, and so on).
If method access is so good, why not just use methods? In my experi-
ence, most property accessors in action beans do nothing more than
just get or set an instance field. If that's the case, then the argument
that you can “do something extra” is pretty irrelevant! Most often, the
only access to these properties is by methods in the declaring class
and by Stripes. But Stripes doesn't need the encapsulation; if you use
a public field today and then decide tomorrow that you want to use
methods, you can simply make the field private, add the methods, and
recompile. Stripes will immediately switch to using the methods instead
of the field. You can even make some properties public and others pri-
vate with methods in the same action bean.
If you can get over the mental hurdle of using public properties, you'll
soon find it much more concise to write (and read) this:
public Date birthDate;
instead of:
private Date birthDate;
public Date getBirthDate() {
return birthDate;
}
public Date setBirthDate(Date birthDate) {
this .birthDate = birthDate;
}
∗. If you want to display the property in a JSP with an EL expression such as
${actionBean.birthDate} , you still have to provide a getter method to satisfy the
JSP specification.
 
 
Search WWH ::




Custom Search