Direct Access

The simplest way to say “I’m fetching data” or “I’m storing data” is to use direct variable access:

x = 10;

Direct variable access has the advantage of clarity of expression. When I read x = 10;, I know exactly what is going to happen. This clarity comes with a loss of flexibility. If I store a value in a variable, that’s all I can do. If I store values into that variable from many parts of the program, then to make a change I will likely have to change all those parts of the program.

The other downside of direct access is that it is an implementation detail, below the level of most of my thoughts while programming. Setting a variable to 1 may cause my garage door to open, but code that reflects this implementation detail won’t communicate well. Compare:

doorRegister = 1;

with:

openDoor();

or, with objects:

door.open();

Most of the thoughts I think while programming have nothing to do with storage. Widespread direct access clutters communication. For those parts of the program where I really am thinking about what is stored where, I use direct access to communicate those thoughts. Storage decisions play a different role for different programmers, so there is no one policy for using direct access that will fit everyone. People keep trying to formulate such rules: direct access only inside accessor methods, and maybe inside constructors too; direct access only inside a single class or inside a class and all its subclasses, or maybe inside an entire package. There is no universal rule. Programmers need to think, communicate, and learn. That’s part of being professional.

Implementation Patterns

contents