Stephan van Hulst wrote:
You mean, almost never, unless you meant "always access fields through methods, rather than directly". Simple getters and setters don't really add a lot of behavior to a class. Getters usually are fine, but only add them when you need them.
I'm going to be contrary again. This goes all the way back to my C++ days.
There are two things that explicit set/get methods offer over direct property access.
First, should it be necessary to attach additional functionality to the set/get process, you need a method. In almost all cases, that's something that you shouldn't do - set/get should be both idempotent as well as lacking in side functionality, but there are exceptions to every rule. And, of course, on "set" methods, you might want to assert only certain values as valid "set" values.
The second is a bit shakier. These days, debuggers can be configured to throw breakpoints on both set and get of variables. In less civilized times, that wasn't so, and thus the advantage of using a method, since you could set a code breakpoint.
However, even today you don't always have a debugger when you need it. You don't run production systems under a debugger, you might want to do paranoid value checking in critical code, stuff like that. You might be going crazy because you know that a value's being used, but you don't know what the accessor is, and without a debugger, only a manually-generated stack trace can help.
So, as a rule, I very much recommend avoiding direct access in favor of get/set. Many IDEs can automate the grunt work of creating the code, so it's minimal work and maximal flexibility. And, give modern optimizers, not likely to cost you anything in run-time overhead over direct access.
Incidentally, the Java Persistence Architecture (JPA) offers 2 different ways to access Entity properties - either via direct (field) access or via property method (get/set) access. It's got to be all one or all the other, however, since JPA re-works the access mechanisms internally.