One more thing ...

The only thing on the agenda for this class is to review one more aspect of object oriented programming. It goes back to our earlier lessons, where the moral of our story was that we wanted the code operating on the fields of an object of class Foo to be a method of class Foo. That idea meant that, when designing a class, we put the focus not on what data should be in the class, but what methods it should have. This is a lesson we all need to learn over an over again. I wanted to provide yet another example of that idea, but this time in the context of GUI programming.

Disobeying the law

The code below produces the world's simplest (and perhaps worst) GUI program: a primitive conversion program, as pictured here:

The version of the program given directly below violates the principle of information hiding. All the fields are public!

Obeying the letter, but not the spirit

For many students, the way to rewrite the above code in the proper Object Oriented way is clear: make the fields private, but add getters and setters for each field, as shown below. Perhaps this follows the letter of the law, but definitely not the spirit. All you've really accomplished is to make a "struct" with a lot of extra code around it. In fact, other than extra code, the structure of the program hasn't changed at all!

Obeying the spirit ... and acheiving enlightenment

Why is the above getter/setter solution not really following the spirit of OOP? Because the getter/setter operations are not natural operations for Convert objects. They're just workarounds, so that you can't be accused of having public fields and violating information hiding. Encapsulation still hasn't been addressed satisfactorily, though. The real point is that the code for updating the Convert panel shouldn't be in ConvListener. It's an operation that manipulates a Convert panel, so it should be a part of Convert.

The solution below gets rid of the getters and setters and adds an "update" method to the Convert class, which tells the convert panel to update itself. That's a proper object oriented solution to this problem.