Java Reference
In-Depth Information
One set of responsibilities that Stock objects should not handle is producing the
console input and output. We need to prompt the user for information and print mes-
sages, but these functions are specific to the current client program. Objects are
meant to be reusable pieces of software, and other programs might wish to track
stock purchases without using these exact messages or prompts. If the Stock class
handles the prompts and printing, it will be heavily intertwined with this client pro-
gram and will not be easily reusable by other clients.
In general, we want to reduce unnecessary dependencies among classes.
Dependencies among classes in an object-oriented program contribute to coupling ,
the degree to which one part of a program depends on another.
Striving to avoid unnecessary coupling is a second design heuristic commonly
used in object-oriented programming. A design that avoids this problem is sometimes
said to have loose coupling.
Let's divide some of the responsibilities now, based on our heuristics. Since the
StockMain client program will perform the console I/O, it should handle the follow-
ing responsibilities:
StockMain
Prompt for each stock's symbol.
Prompt for the number of purchases of each stock.
Read each purchase (number of shares and price per share) from the console.
Print the total profit/loss of each stock.
Compare the two total profits/losses and print a message about which stock gen-
erated higher profits.
Since the StockMain client program will be performing the console I/O, it might
seem natural for it also to store the information about each stock purchase (that is, the
number of shares and the price paid). But our Stock object should contain the func-
tionality to compute a stock's total profit or loss, and it will need to have the data
about all purchases to do so. This leads us to a third design heuristic: Related data
and behavior should be in the same place. With that in mind, we can write out the
responsibilities for the Stock class as follows:
Stock
Store a stock's symbol.
Store accumulated information about the investor's purchases of the stock.
Record a purchase of the stock.
Compute the total profit/loss for the stock.
When they are designing large object-oriented programs, many software engineers
write information about classes as we've done here. A common technique to brain-
storm ideas for classes is to write information on index cards. Each card is called a
 
Search WWH ::




Custom Search