Benad's Web Site

The first time I've seen a diagram describing the "Model-View-Controller" design pattern, it was like this:

Well, I didn't "get it". If I change anything I potentially have to change everything else. So what's the point of having a dependency graph for that?

Recently, searching for building XUL-like GUIs for Java, I came across gui4j. One of the things this framework does is to disallow any code to access the GUI maintained by gui4j in any way. At first I was pissed and tried to figure out a way to make it "coupled" with XMLBeans directly, which is my Model.

But then, once I figured out how to use "Events", things were simpler. The Controller can tell the View, through an Observer pattern, that it needs to "refresh" itself. Then, the View asks the Controller what values it has to put in the GUI elements. The Controller never changes the GUI in any other way.

For the Model, it is used by the Controller to return to the View the values it asked for. The Controller also asks the Model to notify the View Observer whenever something changes in the Model. That way, whenever the Controller changes something in the Model it doesn't have to explicitly tell the View to "refresh" itself (very useful when you have multiple independent Views that edits the same Model). At any rate, the Model and View are uncoupled.

The result? This:

Hmmm... That looks like... Layered...

This is really great when you have to maintain the code for this. In the past writing a GUI editor for XML files in Java would take me > 2000 lines of code. But with XMLBeans and gui4j, I need about 100 lines, and simple ones too. Also, if you think about it, if I change the Model I don't have to change the View at all. And I can the the View without touching anything else, unless I need more "logic" from the Controller. All of this because, in effect, my GUI development is now Layered!

You don't have to use gui4j to get this, but the point remains: High coupling between components is bad, even if in the end you get used to it. Good architecture is always better.

Published on September 8, 2005 at 17:19 EDT

Older post: Java News Sources

Newer post: Frameworks, frameworks, frameworks...