Download COMP 542 Object Oriented Programming
Transcript
COMP 542/4 E 4.1 Winter 2000 16 Design — Choosing the Classes The first step in designing an object oriented program is to find the classes. Actually, we start by looking for candidate classes — entities that might become classes in the final program. There are various ways of finding classes. None of them is foolproof: the best guide is experience. • Look for possible classes in the problem statement. Objects are things, and things are likely to be referred to as nouns. (It is also worth noting that a verb applied to a noun may suggest a method associated with an object.) • You can rewrite the problem statement in your own way, being careful not to change its meaning in any significant way, and look for nouns in your own problem statement. • Consider possible solutions and think about how they might work. A useful technique is to look for scenarios (also sometimes called use cases), which are examples of the way in which the proposed program may work. In practice, looking for nouns tends to produce a large number of candidate classes (see, for example, Figure 2–3 on page 21 of Reiss’s book). Consequently, we need efficient ways of eliminating classes from the list, or of not including them in the first place. • Avoid classes that are too simple. If it looks as if the class would have only a single data member, reject it. If you can’t think of any non-trivial methods for a class, consider rejecting it. • Avoid classes that try to do too much. Nouns that refer to the entire solution or to large parts of it are probably not good classes. The important nouns in the KT problem appear to be: Knight, Board, Tour, Solution, Board, and Move. However, it is not yet clear that all these will be classes in the finished program. It is also important to realize that looking at the problem statement will not suggest all of the classes that may be needed for the solution. We may need “solution related” classes for the user interface, to represent data structures such as the search tree, to embody algorithms needed for the solution, and to “manage” the program’s progress. We should also consider parts of the solution that are likely to change. If possible, these parts should be put in separate classes so that they can be changed easily when the program is finished. The component of the KT solution that is least clear is the heuristic for building the search tree. This suggests that we introduce a class Heuristic; later on, if we want to try various heuristics, we can work within this class. These considerations lead to an expanded list of candidate classes (Figure 2–6 on page 24): Board, Direction, Heuristics, Knight, Move, Search, Solution, Square, Tour, and User Interface. 4.2 The Top-Level Classes Any system of sufficient complexity should have several top-level classes. A top-level class performs a major role in the solution and interacts with other top-level classes in significant