Java Reference
In-Depth Information
The general formula for the profit is the following:
profit
((total shares)
*
(current share price))
(total cost)
The total number of shares and total cost figure needed for this calculation are the
accumulated information from all the purchases that have been made of this stock.
This means that information will need to be stored during each call of the
purchase
method to be used later in the
getProfit
method. A key observation is that we do
not need to store the number of shares, price per share, and cost for every purchase:
We only need to store cumulative sums of the total shares purchased so far and the
total dollars spent so far to acquire those values.
The third value we need in order to calculate the profit is the current share price. We
could choose to make this a field in the
Stock
class as well, but the share price is a
dynamic value that changes regularly. We use it during a single call to the
getProfit
method, but the next call may come at a later date when the price per share has changed.
This problem leads us to another design heuristic: Fields should represent values
of core importance to the object and values that are used in multiple methods. Adding
too many fields clutters a class and can make its code harder to read. If a value is
used in only one method of the class, it's best to make it a parameter to that method
rather than a field. Therefore, we'll make the share price a parameter to the
getProfit
method.
public double getProfit(double currentPrice)
One piece of state that we haven't discussed yet is that each stock has a symbol,
such as
"AMZN"
. We'll store the symbol as a
String
field in each
Stock
object.
Here's a skeleton of our
Stock
class so far:
// incomplete Stock class
public class Stock {
private String symbol;
private int totalShares;
private double totalCost;
...
public double getProfit(double currentPrice) {
...
}
public void purchase(int shares, double pricePerShare) {
...
}
}
Search WWH ::
Custom Search