- 20.1 Programming and Iterative, Evolutionary Development
- 20.2 Mapping Designs to Code
- 20.3 Creating Class Definitions from DCDs
- 20.4 Creating Methods from Interaction Diagrams
- 20.5 Collection Classes in Code
- 20.6 Exceptions and Error Handling
- 20.7 Defining the Sale.makeLineItem Method
- 20.8 Order of Implementation
- 20.9 Test-Driven or Test-First Development
- 20.10 Summary of Mapping Designs to Code
- 20.11 Introduction to the NextGen POS Program Solution
- 20.12 Introduction to the Monopoly Program Solution
20.5 Collection Classes in Code
One-to-many relationships are common. For example, a Sale must maintain visibility to a group of many SalesLineItem instances, as shown in Figure 20.5. In OO programming languages, these relationships are usually implemented with the introduction of a collection object, such as a List or Map, or even a simple array.
Figure 20.5 Adding a collection.
For example, the Java libraries contain collection classes such as ArrayList and HashMap, which implement the List and Map interfaces, respectively. Using ArrayList, the Sale class can define an attribute that maintains an ordered list of SalesLineItem instances.
The choice of collection class is of course influenced by the requirements; key-based lookup requires the use of a Map, a growing ordered list requires a List, and so on.
As a small point, note that the lineItems attribute is declared in terms of its interface.
Guideline: If an object implements an interface, declare the variable in terms of the interface, not the concrete class.
For example, in Figure 20.5 the definition for the lineItems attribute demonstrates this guideline:
private List lineItems = new ArrayList();