Sunday, October 9, 2011

Object Attributes and States, From Modeling to Programming

Regarding things as objects with attributes is a powerful thinking technique,  learned by some of us as early as in elementary school. As an example, in the popular logic game for children, Zoombinis Logical Journey, every zoombini has four attributes. (In the game, the attributes are visually identified without a text name. For our convenience of discussion, we just name them hair, eyes, nose, and feet.)

Zoombini Attributes
An attribute has a value. Legitimate values for a specific attribute may be elements of a finite or infinite set (the domain of the attribute). In the Zoombinis example, each attribute may have one out of five possible values. An object's state is the combination of its attribute values. In the zoombinis example, the particular zoombini in the picture above is in a state that can be described as

A Zoombini State
All possible states of an attribute together form the state space of the attribute. All possible states of all attributes of a object form the state space of the object. All possible states of all objects of a software system form state space of the software system.

An object may be mutable. In that case, its state can be changed. An object may be immutable. In that case, its state cannot be changed.

UML, as the claimed universal modeling language, directly supports the object/attributes thinking techniques. In UML, an object may have many attributes. In UML, we may model zoombinis as objects of a Zoombini class:

Zoombini Class in UML

 Unfortunately, UML does not offer a notation to distinct mutable and immutable attributes.

When we start coding zoombinis in a programming language, we often encounter a problem - most popular programming languages do not have the concept of attributes. For example, in Java, a object may have member fields and member methods, but not attributes. Because attribute is such a powerful concept in our rational thinking, we are unwilling to give it up so easily. What we can do is what Steve McConnell called "programming into a language". Actually, the JavaBean property concept is the same as object attribute. So we can code an object attribute as an object property in Java. For an immutable attribute, just omit the mutator method of the property. However, we can also code an object's mutable attribute as a public field of the object.