Java Reference
In-Depth Information
CRC card and lists the Class, its Responsibilities, and its Collaborators (other classes
to which it is coupled).
The following list summarizes the design heuristics discussed in this section:
A class should be cohesive, representing only one abstraction.
A class should avoid unnecessary coupling.
Related data and behavior should be in the same class.
Note that we began our design by looking at responsibilities rather than by speci-
fying fields as we did when we developed our Point class. We began writing the
Point class by discussing fields because the data associated with a point is simple
and more obvious than the data associated with stock purchases. But in many larger
problems like this one, working backward from behavior and responsibilities is a bet-
ter technique.
Stock Fields and Method Headers
In this section we'll decide on a design for the method names and signatures the
Stock should use to implement its behavior. We'll use this design to determine which
fields are required to implement the behavior.
We've decided that a Stock object should allow clients to record purchases and
request the total profit or loss. Each of these tasks can be represented as a method.
The recording of a purchase can be represented as a method called purchase . The
retrieval of the total profit or loss can be represented as a method called getProfit .
The purchase method should record information about a single purchase. A pur-
chase consists of a number of shares that the user bought (which we can assume is a
whole number) and a price per share (which can include real numbers with both dol-
lars and cents). Our purchase method should accept two parameters: an int for the
number of shares bought and a double for the price per share. The method can use a
void return type, since nothing needs to be returned after each purchase is recorded:
public void purchase(int shares, double pricePerShare)
The getProfit method will return the amount of money that the user made or
lost on all accumulated purchases of this stock. Consider an investor who has made
the following three purchases of a stock:
Purchase #1: 20 shares * $10 per share = $ 200 cost
Purchase #2: 20 shares * $30 per share = $ 600 cost
Purchase #3:
10 shares * $20 per share = $ 200 cost
50 total shares,
$1000 total cost
If today's price per share is $22.00, the current market value of the investor's 50
shares is (50 * 22) or $1100. Since the investor paid $1000 total for the shares and
they are now worth $1100, the investor has made ($1100 - $1000) = $100 of profit.
 
Search WWH ::




Custom Search