Parameterized Class

Parameterized Class

Several languages, most noticeably C++, have the notion of a parameterized clasys, or template.

This concept is most obviously useful for working with collections in a strongly typed language. This way, you can define behavior for sets in general by defining a template class Set.

     class Set <T> {
         void insert (T newElement);
         void remove (T anElement);


When you have done this, you can use the general definition to make set classes for more specific elements.

         Set <Employee> employeeSet;


You declare a parameterized class in the UML using the notation shown in Figure 6-18.

Figure 6-18. Parameterized Class

The T in the diagram is a placeholder for the type parameter. (You may have more than one.) In an untyped language, such as Smalltalk, this issue does not come up, so this concept is not useful.

A use of a parameterized class, such as Set<Employee>, is called a bound element.

You can show a bound element in two ways. The first way mirrors the C++ syntax (see Figure 6-19).

Figure 6-19. Bound Element (Version 1)

The alternative notation (see Figure 6-20) reinforces the link to the template and allows you to rename the bound element.

Figure 6-20. Bound Element (Version 2)

The bind stereotype is a stereotype on the refinement relationship. This relationship indicates that EmployeeSet will conform to the interface of Set. In specification terms, the EmployeeSet is a subtype of Set. This fits the other way of implementing type-specific collections, which is to declare all appropriate subtypes.

Using a bound element is not the same as subtyping, however. You are not allowed to add features to the bound element, which is completely specified by its template; you are adding only restricting type information. If you want to add features, you must create a subtype.

Parameterized classes allow you to use a derived typing. When you write the body of the template, you may invoke operations on the parameter. When you later declare a bound element, the compiler tries to ensure that the supplied parameter supports the operations required by the template.

This is a derived typing mechanism because you do not have to define a type for the parameter; the compiler figures out whether the binding is viable, by looking at the source of the template. This property is central to the use of parameterized classes in C++'s standard template library (STL); these classes can also be used for other interesting tricks.

Using parameterized classes does have repercussionsfor example, they can cause considerable code bloat in C++. I rarely use parameterized classes in conceptual modeling, mostly because they are used mainly for collections, which are implied by associations. (One case I do use it for is the Range pattern; see Fowler 1997). I use parameterized classes in specification and implementation modeling only if they are supported by the language I am using.