< Day Day Up > |
Gilbert and McCarty describe cardinality as the number of objects that participate in an association and whether the participation is optional or mandatory. To determine cardinality, ask the following questions:
For example, let's consider the following example. We are creating an Employee class that inherits from Person, and has relationships with the following classes:
What do these classes do? Are they optional? How many does an Employee need?
To sum up, Table 9.1 represents the cardinality of the associations of the classes we just considered . Table 9.1. Cardinality of Class Associations
Cardinality Notation The notation of 0 1 means that an employee can have either zero or one spouse. The notation of 0 n means that an employee can have any number of children from zero to an unlimited number. The n basically represents infinity. Figure 9.7 shows the class diagram for this system. Note that in this class diagram, the cardinality is indicated along the association lines. Refer to Table 9.1 to see whether the association is mandatory. Figure 9.7. Cardinality in a UML diagram.
Multiple Object AssociationsHow do we represent an association that might contain multiple objects (like 0 to many children) in code? Here is the code for the Employee class: import java.util.Date; public class Employee extends Person{ private String CompanyID; private String Title; private Date StartDate; private Spouse spouse; private Child[] child; private Division division; private JobDescription[] jobDescriptions; public String getCompanyID() {return CompanyID;} public String getTitle() {return Title;} public Date getStartDate() {return StartDate;} public void setCompanyID(String CompanyID) {} public void setTitle(String Title) {} public void setStartDate(int StartDate) {} } Note that the classes that have a one-to-many relationship are represented by arrays in the code: private Child[] child; private JobDescription[] jobDescriptions; Optional AssociationsOne of the most important issues when dealing with associations is to make sure that your application is designed to check for optional associations. This means that your code must check to see whether the association is null . Suppose in the previous example, your code assumes that every employee has a spouse. However, if one employee is not married, the code will have a problem (see Figure 9.8). If your code does indeed expect a spouse to exist, it may well fail and leave the system in an unstable state. The bottom line is that the code must check for a null condition, and must handle this as a valid condition. Figure 9.8. Checking all optional associations.
For example, if no spouse exists, the code must not attempt to invoke a spouse method. This could lead to an application failure. Thus, the code must be able to process an Employee object that has no spouse. |
< Day Day Up > |