Monday, February 25, 2013

Bidirectional and Directed Associations

Associations allow classes to interact.  By interact, we mean calling an operation or accessing data.  In code, pointers or references implement associations in object oriented languages.    Functional languages, such as C, use pointers or references when passing data, but only require #include for accessing operations.

Technically, the previous paragraph isn’t right, is it?  Associations don’t allow classes to interact, they allow objects to interact.  UML Links instantiate associations.  That is, an association defines a generic pointer whereas a link defines a pointer to a specific object.  For simplicity sake, though, we’ll continue to discuss this subject in terms of classes and associations.

In the previous diagram, the line between Sensor and GenericDetector represents a bidirectional association.  That means that Sensor “knows” about (has a pointer to) GenericDetector and GenericDetector knows about Sensor.  Sensor refers to GenericDetector with the name itsDetector.  Similarly, GenericDetector refers to Sensor as itsSensor.  So, an object of type GenericDetector could call the Sense operation of an object of type Sensor.  In C++, the code would look like this:

     itsSensor->Sense();

Most of the time, however, only one of the two classes involved in the interaction needs a pointer to the other.  In fact, requiring bidirectional associations is generally considered bad design because it makes the software harder to reuse and to extend.  Instead, use directed associations, as shown in the attached figure.  Here, Sensor can call Reset() or ToggleValue(), but GenericDetector cannot call Sense.

No comments:

Post a Comment