Java Reference
In-Depth Information
One possible design would be to create a Purchase class that records information
about a single purchase of shares of a particular stock. For example, if the user speci-
fied three purchases, the program should construct three Purchase objects. However,
a more useful abstraction here would be to hold the overall information about all pur-
chases of one stock in one place. The investor may make many purchases of the same
stock, so you want to have an easy way to accumulate these shares and their total cost
into a single object.
Therefore, instead of a Purchase class, we'll write a Stock class. Each Stock
object will keep track of the investor's accumulated shares of one stock and can pro-
vide profit/loss information. Our Stock class will reside in a file called Stock.java ,
and the client program itself will reside in a separate file called StockMain.java .
Object-Oriented Design Heuristics
We now face the important task of deciding on the contents of our Stock class. It can
be tricky to choose a good set of classes and objects to solve a complex programming
problem. Chapter 4's case study introduced a set of procedural design heuristics ,or
guidelines for good design, for effectively dividing a problem into methods. There
are similar guidelines for effectively breaking a large program into a set of classes
and objects. The heuristics we'll discuss here are based on those listed in computer
scientist Arthur Riel's influential book, Object-Oriented Design Heuristics .
First let's look at the overall set of responsibilities, the things that a class must
know or do to solve the overall problem:
Prompt the user for each stock's symbol and store the information somewhere.
Prompt the user for the number of purchases of each stock.
Read each purchase (number of shares and price per share) from the console and
store the information somewhere.
Compute the total profit/loss of each stock.
Print the total profit/loss of each stock to the console.
Compare the two total profits/losses and print a message to the console about
which stock performed better.
It might be tempting to make most or all of these tasks responsibilities of our
Stock class. We could make a Stock object store all the purchases of both stocks,
prompt for information from the console, print the results, and so on. But a key
guideline when writing classes is that they should have cohesion.
Cohesion
The extent to which the code for a class represents a single abstraction.
Placing all the responsibilities in the Stock class would not allow that class to rep-
resent a single clear abstraction. The abstraction we want to represent in the Stock
class is the accumulated purchases of a single stock.
 
Search WWH ::




Custom Search