Sponsored Link •
Bill Venners: Why are fields in entries public?
Ken Arnold: We could have used typical accessors, such as
set methods. In any pair of
set methods, such as in a
JavaBean, there's a contract. The documentation of the JavaBean says
that setting this value will result in the following behavior. One option,
for example, could define
get as "get next," where the
returned value monotonically increases.
set could mean
"set the starting point,"—reset where the value returned by
get monotonically increases from. That is a legitimate
set contract. In random number
generators, for example, you set the seed and get the next random
The contract for
set methods of
entries would essentially be: if you call
set with a given
value, and then return later and call
get with no
set, the value would be the same—it would
be unmodified. Furthermore, remember the matching is exact. When
set on your template to set a particular value
to 17, you are asking for an entry where the value is 17. When you
receive an entry and call its
get method, you better get
17, not 18. Incrementing is not OK.
So if you examine the contract description for an entry's
set methods, you would see it
describes a field.
have to act exactly like a field. Therefore, we asked ourselves, why
should we have
whose behavior is exactly like this other language construct called a
field? Why not just make it a field? If we make it a field, it will have
the correct behavior. Nobody can accidentally screw up their
set methods. Making it a field
eliminates a source of error.
Now this sometimes makes people uncomfortable because they've been told not to have public fields; that public fields are bad. And often, people interpret those things religiously. But we're not a very religious bunch. Rules have reasons. And the reason for the private data rule doesn't apply in this particular case. It is a rare exception to the rule. I also tell people not to put public fields in their objects, but exceptions exist. This is an exception to the rule, because it is simpler and safer to just say it is a field. We sat back and asked: Why is the rule thus? Does it apply? In this case it doesn't.