Saturday 27 December 2008

Item 14: In public classes, use accessor methods, not public fields

This item is applicable to all object orientated languages, not just to Java. Encapsulation and abstraction are both well understood and I do not believe there is a lot to argue with in general.

The item explains that classes should not contain public instance fields and should instead use private instance fields, getters and, in the case of mutable classes, setters. The advantage being that you can change the classes implementation without having to change its interface. All standard stuff.

There are, however, two things worth discussing. Bloch suggests that it may be acceptable to make immutable (final) instance fields public and instance fields within classes that are package-private or private-nested public.

Paul Grenyer

No comments: