Model classes not roles

From CSSEMediaWiki
Revision as of 02:01, 23 July 2009 by Aidan Bebbington (Talk | contribs)
Jump to: navigation, search
Be sure the abstractions that you model are classes and not simply the roles objects play. --Riel's Heuristic 2.11, Arthur Riel 1996

Make sure that the abstractions you model are classes that have separate behaviour, not just the roles that objects play. If in the domain you are modeling there are potential classes that have the same behaviour, then they are probably different roles that the same class plays.

For example consider we want to model a university which consists of Students and Lecturers. We could make Student and Lecturer separate classes, or we could make student and lecturer different roles that a Person class might play. If Students and Lecturers exhibit different behaviours then we should probably model them as separate classes. If they have the same behaviour, then we should probably model a Person class that can play the role of student or lecturer.

Before creating new classes ensure that the behaviours are different, and that the new classes are not simply roles of another class that use a subset of the existing functionality. Riel states that it is ok for an object to use only a subset of the class's behaviour.

Interestingly Riel also states that there is a missing heuristic waiting to be discovered, to do with determining when to model a new class or a role of an existing class. It seems to depend on the domain and gets harder to determine in abstract domains. In general, if any of the public interface of a class cannot be used in a given role, then a new class is needed for the role. For example if an operation of a lecturer is giveLecture(), then Lecturer should be a separate class as a Student cannot give a lecture (in the traditional sense). However we could have a turnOnProjector() method that only lecturer's are meant to use, but a student could use if necessary. In this case lecturer and student are just roles of the Person class.

See also

Personal tools