Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^180) | Selection and Encapsulation
day conversion formulas handle those rules; the other responsibilities merely perform sim-
ple arithmetic on the Julian day number.
A user can simply imagine that every Dateresponsibility is separately computing leap
years. Control abstraction lets us actually program a more efficient implementation and
then hide that complexity from the user.
To see how we can apply these principles, let’s revisit our design for theNameclass, mak-
ing it more general, and thus making it a more complete abstraction of a realNameobject. In
terms of data abstraction, a typical name consists of three parts: first name, middle name,
and last name. Less typical name structures include having two middle names or having no
middle name. Many names also have a prefix, such as “Dr.” or “Rev.”; others have suffixes such
as “Jr.” or “III”. Adding these possibilities to our existingNameclass abstraction merely requires
us to provide more fields to hold the values and some methods to access them. We might
also extend the methods that format the name to include the new information as appro-
priate. We won’t change the data abstraction of the Name class here, because it just makes
the example code longer without demonstrating any new concepts. The Case Study Follow-
Up exercises include some problems that ask you to make these additions.
Now let’s turn our attention to the control abstraction of Name. Here are the responsibil-
ities that Namecurrently supports:
We have two ways to create a new Name: one that hides a series of interactions with the
user via the Systemclass, and another that merely copies the arguments to its internal fields.
Abstraction allows us to make these constructors do very different things, while presenting
similar functionality through the interface. As far as the user code is concerned, calling a Name
constructor builds a new Nameobject. How it happens doesn’t matter.
A Namecan return its contents in three specific formats. But what if we want a Namein a
different format? We could try to create a method for every imaginable format, but that
would be a lot of work and we’d still undoubtedly miss at least one format that a user would
want. Alternatively, we can let the user construct any name formats that aren’t provided, if
we provide methods that return the parts of the name as strings. So we should add the fol-
lowing responsibilities to our design for Name:
knowFirstName() returns String
knowMiddleName() returns String
knowLastName() returns String
new Name()
new Name(first, last, middle)
firstLast() returns String
full() returns String
lastFirstMI() returns String
T
E
A
M
F
L
Y
Team-Fly®

Free download pdf