On Fri, 12 Jul 2013 16:01:30 +0100, sebb wrote:
On 12 July 2013 15:39, Ajo Fod <ajo....@gmail.com> wrote:
I wonder what conditions justify the use of protected / public
fields?
I can see how protected fields make more sense for a single user
code
because it is easier to not have all those getter/setter methods.
But
perhaps for an API with a wide audience, the commitment of providing
a
field is a big one. Is this the general view?
IMO there is one use case for which a protected field is suitable,
and
that is a constant which only has use in the class hierarchy.
Even for that one, a getter is better. For example, if you later
wanted to move that constant to another class, you'd be stuck (if
backward-compatibility must be retained).
[Some of these occurrences exist(ed) in CM.]
Getters are much more flexible, and should be quickly inlined by the
compiler at run-time.
Setters should be used sparingly; prefer immutable classes where
possible.
Remember that the Java memory model permits threads to cache
variables
unless prevented by synchronisation.
If thread A modifies field F, thread B may not see the updated value
of field F immediately or at all.
Unless F is volatile, or unless A & B both synch. on the *same* lock.
Using getters/setters is one way to guarantee safe publication - make
both methods synchronised on the same lock.
Properly encapsulated classes are much easier to test, as the fields
cannot change unexpectedly.
Classes with exposed mutable fields are basically impossible to test
fully in a multi-threaded environment, and not always easy in a
single-threaded environment.
+1
Gilles
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscr...@commons.apache.org
For additional commands, e-mail: dev-h...@commons.apache.org