Get the book!

Tip of the Week: Value Objects

Posted by Eitan Suez Fri, 04 Aug 2006 06:28:00 GMT

Shedding Light on JMattter's Design. Part 1: Value Objects

The notion behind Value Objects is old. It actually dates back to a specific version of Smalltalk. I am not a Smalltalk programmer but I have read a little bit about Smalltalk. It was in that environment that the concept of MVC first arose. The book, The Art and Science of Smalltalk describes value objects.

In Java, everything has a getter and setter. The notion of the value object is that, instead of replacing the reference with another value, the reference stays constant, but its value changes.

So, instead of:

  String name;
  public String getName() { return name; }
  public void setName(String name) { = name; }

We do:

  final String name = new String("Some Initial Value");
  public String getName() { return name; }

And, to change the value of the name, we do:

  name.setValue("Some new Value");

I see two advantages to this. The first is that you avoid nullpointer exceptions if you erroneously try to manipulate a null property.

The second is much more important: if the reference stays constant, then when the time to build a user interface on top of my model, then I can setup views for all my properties, and each view (or renderer, or editor) can set itself up to listen to changes on its corresponding value. When the value changes, the model object fires a change event that allows the view to update itself.

When not using Value Objects, it's much more difficult, and more expensive to try to set up MVC: each time a value is set, the view must detach itself from the old value and attach itself anew to the old value. It's useless busy work. The alternative, of course, is for the view to attach itself as a listener on a property of the parent object. I picked the former. And it worked out nicely.

I can simply use the Value Object mechanism essentially to define by-value semantics on properties. This is how JMatter can distinguish a aggregation from an association, for example.

1 comment


  1. Sam Griffith said about 3 hours later:

    ValueModels have a long history and go back into both Smalltalk-76 and Lisp (InterLisp) at Xerox Parc. These papers might shed more light on the power of valuemodels. Additionally note that Groovy has support for valuemodels as well and due to the late binding, you can write code almost exactly like the Smalltalk code that is shown in the examples in these papers. I suggest you may want to really dig into there use in these papers and in VisualWorks. They are great for adapters, filters, etc.

    Paper by person who wrote up pattern in PLOP 1 book.

    JGoodies version:

    Groovy version:

    Use in VisualWorks:

    Use in Swing:

    Relevant links:

Comments are disabled