Home > Articles > Programming

Just Typical: UML Stereotypes and Class Archetypes

📄 Contents

  1. Extending UML with Stereotypes
  2. Conclusion
What effects does a UML mechanism have on the way programmers work with code? In the third article in a series introducing UML from a programmer's perspective, Stephen Palmer looks at how UML's stereotype extension mechanism can be put to good use by Java programmers.
Like this article? We recommend

Welcome to the third article in a series introducing UML and object modeling from a Java programmer's perspective. In the previous articles, we introduced UML class diagrams comparing the way classes and relationships between classes are represented in the Unified Modeling Language (UML) and the Java programming language. In those articles, we started with Java source code and looked at how that could be represented graphically using the UML. In this article, we start from the opposite end and look at the effect a UML mechanism has on the way we work with our code.

Extending UML with Stereotypes

UML has a number of mechanisms that can be used to extend its core concepts. Probably the most widely known are stereotypes. UML stereotypes can be used to further define an element in a UML diagram. By default, stereotypes are depicted as a keyword surrounded by guillemot characters, the quote marks used in several European languages. Because guillemots look like two angle brackets, this is an accepted alternative representation for those of us who do not have ready access to European characters on our keyboards or who use more traditional computer systems.

Stereotypes can be applied to almost anything in the UML, including classes, attributes, operations, and associations in class diagrams. For example, we can use stereotypes to show a categorization of classes in our diagrams. Figure 1 shows stereotypes being used to indicate the role played by a class in a version of the popular state pattern adapted from the Design Patterns book by Gamma, et al1. UML defines a large number of standard stereotypes2, and we can use these or define our own, as shown in Figure 1.

Figure 1Figure 1 UML stereotypes used to show the role of a class in a design pattern.

Notational Note

The MessageStatus interface in Figure 1 should officially have the word interface within guillemots or pairs of angled brackets. However, the implementers of the Together ControlCenter3 product used to produce the figure decided to leave them out to distinguish interfaces from other stereotypes because unlike other stereotypes, "Interface is a peer of Class within the UML metamodel (both are Classifiers)."2

Historical Note

Until UML 1.4 (September 2001), a diagram element in the UML could have only a single stereotype. With UML 1.4, the Object Management Group lifted this restriction, and a diagram element may now have multiple stereotypes. Many UML modeling tools have yet to catch up and do not yet offer this particular feature.

This is all very well, and stereotypes are obviously useful in clarifying the use of something in a diagram, but how does that affect our Java source code? At one level, the answer is "not at all;" there is nothing in Java that enables us to categorize classes in this way (inheritance and interfaces were discussed in the previous article and have their own special representations in UML). However, at another level, we can start to use conventions to further communicate the meaning of our source code clearly and concisely. By agreeing on the meaning of a stereotype, we can include that stereotype as a new javadoc tag in our source code comments and reduce the amount of textual comment we need to write to communicate the purpose of our class. Tools that can be taught to recognize those tags can help generate or verify code that does indeed conform to the agreed convention. The following source code shows the skeleton of the Sent class from Figure 1 with the stereotype added as a custom javadoc tag.

/**
 * @stereotype concreteState
 * @author Steve Palmer
 * @version 0.0001
 */
public class Sent implements MessageStatus {
}

Classes are not the only things in the UML that can be given stereotypes to constrain their definition. Figure 2 shows a dependency relationship between two classes using a stereotype to indicate the type of dependency; in this case, objects of the Factory class are responsible for creating objects of the Item class. The source code that follows Figure 2 shows one possible custom javadoc tag that could be used to describe this dependency clearly and concisely.

Notational Note

We have seen three different kinds of relationship drawn between classes in the previous articles. This is the fourth. Associations are drawn with a solid line and an open arrowhead if the relationship is traversable in only one direction. Generalizations are drawn with a solid line and a closed arrowhead from subclasses to the superclass. Realizations are drawn as dashed lines with a closed arrowhead from an implementation to an interface. Now, we have the fourth and final combination of arrowheads and line types: dependencies drawn as dashed lines with open arrowheads from the dependent class.

Figure 2Figure 2 UML dependency relationship further defined by the instantiate stereotype.

public class Factory
{
  /**
   * @dependency <<instantiate>> Item 
   * @return a new Item
   */
  public Item createItem() {
		return new Item();
  }
}

Operations and attributes can also be given stereotypes. Figure 3 shows a class with two operations stereotyped to indicate whether or not they modify the values of the attributes of their objects. The source code that follows shows again the use of a custom javadoc tag to communicate the stereotype.

Figure 3Figure 3 Operations with UML stereotypes.

public class Sale
{
	...


  /**
   * @stereotype query
   * @return total price of sale
   */
  public BigDecimal calcTotal() {
  }


	...


  /**
   * @stereotype update
   * @param price the cost of a single unit of the product being sold
   */
  public void setPricePerUnit(BigDecimal price) {
    this.price = price;
  }


...

}

The reward for doing the extra work of adding the custom javadoc tags to our code is not only less comment text to write, but the opportunity for tools to process those tags and do the following:

  • Regenerate more complete UML diagrams from our source code than otherwise possible.

  • Generate additional information in Javadoc style output.

My favorite modeling tool, TogetherSoft's Together ControlCentre3, uses exactly this sort of approach to store all the extra semantic information from a UML class diagram that cannot be expressed directly in Java source code. However, more modest tools can quite easily be created using Javadoc doclets or any other text file processing engine.

Shape Shifters

At the beginning of the article, we said that angle brackets and guillemots were the default way of showing a stereotype. Stereotypes can also be shown by a change of graphic symbol or shape. Figure 4 shows an example of two classes with the <<actor>> stereotype. The Cashier class is drawn using the alternative symbol for the <<actor>> stereotype, and the Manager class is drawn using the default representation. With the alternative symbol, it is not easy to list the attribute and operations so they are normally omitted from the diagram. A third representation that places a small version of the alternative symbol to the right of the class name in the usual rectangle symbol is also allowed and is becoming increasingly popular in recent times.

Figure 4Figure 4 An alternative icon for the actor stereotype next to the default representation.

There is one big disadvantage of using the alternative graphical symbol approach when drawing class diagrams. If some people are unfamiliar with the symbols being used, it can become much harder to understand what is going on. Also, additional symbols add to the burden of learning to read the diagrams. In these articles, we have deliberately concentrated on the subset of UML class diagram notation most frequently used. There is more than enough additional notation in the UML class diagram standard without adding a vast number of custom shapes and symbols. Fortunately, the UML standard2 does rather begrudgingly allow us an alternative.

In Glorious Color

Instead of changing the shape of a symbol when it's given a certain stereotype, we can change the color or the texture of the diagram element. Using color means that we can retain the usual graphical shapes and symbols, while adding the same (if not more) visual impact that the use of different shapes gives. Also, unlike a set of abstract shapes, a simple color-coding scheme is very easily learned by both developers and client representatives.

Figure 5Figure 5 Modeling in color.

Figure 5 shows a color-coded class diagram using Peter Coad et al's4 four class archetype categorization to further define classes.

The pink <<moment-interval>> classes represent events or activities that we need to keep track of for business or legal reasons in our systems. Examples of pink classes are CarSale and CarRental.

The yellow <<role>> classes represent a way of participating in an event or activity by a green entity class. Examples of yellow classes are CarSalesperson and Customer.

Green entity classes are further categorized into <<party>> (usually a person or organization), <<place>> (the location where the event or activity occurs), and <thing>> (the real-world objects involved in the event or activity).

The fourth archetype is the blue catalog-entry-like-description (<<description>> for short), and represents the difference between something like a physical car on someone's drive and a description of the model of that car in the showroom catalog. The car model is the blue class, and it contains a number of values and ranges of values that hold for all cars of that model; each physical car is represented by a green <<thing>> class.

Classes belonging to a particular class archetype have more or less the same sort of attributes and operations. Classes of particular archetypes also tend to interact with classes of other archetypes in generally predictable ways. These patterns of characteristics and behavior can help us very rapidly build robust and extensible object models, quickly identify attributes and operations that we might otherwise miss, and give us increased confidence in the structure of our code. Figure 5 shows the sorts of attributes and operations we might find in classes of each archetype, and also the most typical way in which the archetypes tend to relate to each other.

Historical Note

The more or less nature of the patterns communicated by class archetypes eventually resulted in the use of the term archetype instead of the tighter patterns typically associated with the English word stereotype. The confusing use of UML stereotypes to textually indicate the archetype of a class and the appropriateness of each of those terms are topics best discussed over beer and pizza when deadlines have been met.

To Color or Not to Color

The UML specification discourages the use of color because of the difficulty it causes color blind people and the problems of greyscale printers, copiers, and fax machines. However, continuing to display the stereotype in its usual textual form enables the most severely color-blind to participate; and with an appropriate choice of primary colors, keeps the diagrams readable when greyscaled by color-challenged devices, as shown in Figure 6.

Figure 6Figure 6 A grayscaled color-coded diagram

When working informally, I use four pads of different colored, three-inch square Post-itTM notes to represent classes on flipchart pads drawing associations with a suitable marker pen.

In the same way that after you have watched color television or seen color photographs, you do not want to return to black and white except for nostalgic reasons, most people never want to return to the shallowness of the black-and-white version once they have experienced object modeling in color.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020