Thank you

Sorry

It's a 25-year-old principle of object-oriented (OO) design that you shouldn't expose an object's implementation to any other classes in the program. The program is unnecessarily difficult to maintain when you expose implementation, primarily because changing an object that exposes its implementation mandates changes to all the classes that use the object.

Unfortunately, the getter/setter idiom that many programmers think of as object oriented violates this fundamental OO principle in spades. Consider the example of a Money class that has a getValue() method on it that returns the "value" in dollars. You will have code like the following all over your program:

The problem with this approach is that the foregoing code makes a big assumption about how the Money class is implemented (that the "value" is stored in a double). Code that makes implementation assumptions breaks when the implementation changes. If, for example, you need to internationalize your application to support currencies other than dollars, then getValue() returns nothing meaningful. You could add a getCurrency(), but that would make all the code surrounding the getValue() call much more complicated, especially if you persist in using the getter/setter strategy to get the information you need to do the work. A typical (flawed) implementation might look like this:

This change is too complicated to be handled by automated refactoring. Moreover, you would have to make these sorts of changes everywhere in your code.

The business-logic-level solution to this problem is to do the work in the object that has the information required to do the work. Instead of extracting the "value" to perform some external operation on it, you should have the Money class do all the money-related operations, including currency conversion. A properly structured object would handle the total like this:

Money total = ...;
Money amount = ...;
total.increaseBy( amount );

The add() method would figure out the currency of the operand, do any necessary currency conversion (which is, properly, an operation on money), and update the total. If you used this object-that-has-the-information-does-the-work strategy to begin with, the notion of currency could be added to the Money class without any changes required in the code that uses Money objects. That is, the work of refactoring a dollars-only to an international implementation would be concentrated in a single place: the Money class.

The problem

Most programmers have no difficulty grasping this concept at the business-logic level (though it can take some effort to consistently think that way). Problems start to emerge, however, when the user interface (UI) enters the picture. The problem is not that you can't apply techniques like the one I just described to build a UI, but that many programmers are locked into a getter/setter mentality when it comes to user interfaces. I blame this problem on fundamentally procedural code-construction tools like Visual Basic and its clones (including the Java UI builders) that force you into this procedural, getter/setter way of thinking.

(Digression: Some of you will balk at the previous statement and scream that VB is based on the hallowed Model-View-Controller (MVC) architecture, so is sacrosanct. Bear in mind that MVC was developed almost 30 years ago. In the early 1970s, the largest supercomputer was on par with today's desktops. Most machines (such as the DEC PDP-11) were 16-bit computers, with 64 KB of memory, and clock speeds measured in tens of megahertz. Your user interface was probably a stack of punched cards. If you were lucky enough to have a video terminal, then you may have been using an ASCII-based console input/output (I/O) system. We've learned a lot in the past 30 years. Even Java Swing had to replace MVC with a similar "separable-model" architecture, primarily because pure MVC doesn't sufficiently isolate the UI and domain-model layers.)

So, let's define the problem in a nutshell:

If an object may not expose implementation information (through get/set methods or by any other means), then it stands to reason that an object must somehow create its own user interface. That is, if the way that an object's attributes are represented is hidden from the rest of the program, then you can't extract those attributes in order to build a UI.

Note, by the way, that you're not hiding the fact that an attribute exists. (I'm defining attribute, here, as an essential characteristic of the object.) You know that an Employee must have a salary or wage attribute, otherwise it wouldn't be an Employee. (It would be a Person, a Volunteer, a Vagrant, or something else that doesn't have a salary.) What you don't know—or want to know—is how that salary is represented inside the object. It could be a double, a String, a scaled long, or binary-coded decimal. It might be a "synthetic" or "derived" attribute, which is computed at runtime (from a pay grade or job title, for example, or by fetching the value from a database). Though a get method can indeed hide some of this implementation detail, as we saw with the Money example, it can't hide enough.

So how does an object produce its own UI and remain maintainable? Only the most simplistic objects can support something like a displayYourself() method. Realistic objects must:

Display different views of themselves (one view might display all the attributes; another might display only a subset of the attributes; and a third might present the attributes in a different way).

Display themselves in different environments (client side (JComponent) and served-to-client (HTML), for example) and handle both input and output in both environments.

Some of the readers of my previous getter/setter article leapt to the conclusion that I was advocating that you add methods to the object to cover all these possibilities, but that "solution" is obviously nonsensical. Not only is the resulting heavyweight object much too complicated, you'll have to constantly modify it to handle new UI requirements. Practically, an object just can't build all possible user interfaces for itself, if for no other reason than many of those UIs weren't even conceived when the class was created.

Build a solution

This problem's solution is to separate the UI code from the core business object by putting it into a separate class of objects. That is, you should split off some functionality that could be in the object into a separate object entirely.

This bifurcation of an object's methods appears in several design patterns. You're most likely familiar with Strategy, which is used with the various java.awt.Container classes to do layout. You could solve the layout problem with a derivation solution: FlowLayoutPanel, GridLayoutPanel, BorderLayoutPanel, etc., but that mandates too many classes and a lot of duplicated code in those classes. A single heavyweight-class solution (adding methods to Container like layOutAsGrid(), layOutAsFlow(), etc.) is also impractical because you can't modify the source code for the Container simply because you need an unsupported layout. In the Strategy pattern, you create a Strategy interface (LayoutManager) implemented by several Concrete Strategy classes (FlowLayout, GridLayout, etc.). You then tell a Context object (a Container) how to do something by passing it a Strategy object. (You pass a Container a LayoutManager that defines a layout strategy.)

The Builder pattern is similar to Strategy. The main difference is that the Builder class implements a strategy for constructing something (like a JComponent or XML stream that represents an object's state). Builder objects typically build their products using a multistage process as well. That is, calls to various methods of the Builder are required to complete the construction process, and the Builder typically doesn't know the order in which the calls will be made or the number of times one of its methods will be called. Builder's most important characteristic is that the business object (called the Context) doesn't know exactly what the Builder object is building. The pattern isolates the business object from its representation.

The best way to see how a simple builder works is to look at one. First let's look at the Context, the business object that needs to expose a user interface. Listing 1 shows a simplistic Employee class. The Employee has name, id, and salary attributes. (Stubs for these classes are at the bottom of the listing, but these stubs are just placeholders for the real thing. You can—I hope—easily imagine how these classes would work.)

This particular Context uses what I think of as a bidirectional builder. The classic Gang of Four Builder goes in one direction (output), but I've also added a Builder that an Employee object can use to initialize itself. Two Builder interfaces are required. The Employee.Exporter interface (Listing 1, line 8) handles the output direction. It defines an interface to a Builder object that constructs the representation of the current object. The Employee delegates the actual UI construction to the Builder in the export() method (on line 31). The Builder is not passed the actual fields, but instead uses Strings to pass a representation of those fields.

Listing 2 shows the source for the JComponentExporter. As you can see, all the UI-related code is concentrated in the Concrete Builder (the JComponentExporter), and the Context (the Employee) drives the build process without knowing exactly what it's building.