Programming and Problem Solving with Java

(やまだぃちぅ) #1

CASE STUDY^185


compare them directly. If we later change the representation (perhaps by using type
charto save space), the modification could cause the dependent user code to fail.
Instead, we need a way to indicate a status that is encapsulated. (Notice how we’re ap-
plying means-ends analysis in this problem-solving process.)
What means do we have for representing a set of values that the user cannot
change, and that the class can make available to the user without exposing the type? It
sounds like a set of public named constants. Would this approach work? Well, the user
needs to know only the names and which methods use them. The type doesn’t need to
be specified. We could tell the user that it is okay to compare the constants with the re-
lational operators, but we would retain more control if we provide equalsand compareTo
methods for this purpose. That way, if we change the representation later, we don’t
have to preserve the property of being comparable using relational operators. Also, if
we use comparison methods that compare a class constant with the status field of the
object, we don’t even have to return the status value to the user code. In this way, we
avoid having to write a separate knowStatusmethod. Let’s give the constants the follow-
ing names:


FAILING
MARGINAL
PASSING


The class should provide methods that return the values that the user code stores in
a record. We can simply return a Name, and the user code can use the methods in Name
that return the parts of the name. To return a score, we could use a separate method to
return each score, or we could use a method that takes a score number as a parameter
and returns the corresponding value. Let’s try the latter strategy. If we ever want to
change the record to include more scores, we wouldn’t have to keep adding a method
for each one. Instead, we could just change the one method to accept a wider range of
score numbers. Let’s list the responsibilities of this class:


Now we have a class with an interface that presents an abstraction of a student
record object. Next, we turn to the algorithms for the individual responsibilities. Let’s
begin with the constructor. First we assign the values of the parameters to the fields of
the object. Then we compute the average and determine the student’s status.
To calculate the average, we must add the three test scores and divide by 3. To assign
the appropriate status, we must determine whether the average is at least 70 for pass-
ing or at least 60 for marginal; otherwise, it is failing. We can use a nested ifcontrol
structure to test these conditions.


new Student (student name, score1, score2, score3)
knowName() returns Name
knowScore(int number) returns int
equalStatus(class constant) returns Boolean
Free download pdf