Java Reference
In-Depth Information
Listing 3.9
The chargeToAccount() method of the AccountingImpl class
public void chargeToAccount(String name, double purchaseAmount) {
CustomerImpl customer = getCustomer(name);
if (customer == null)
customer = new CustomerImpl();
Make new customer
if needed
Persist new
double currentLevel = customer.getBalance();
double creditLimit = customer.getCreditLimit();
double newBalance = currentLevel + purchaseAmount;
if (newBalance <= creditLimit) {
} else {
throw new IllegalArgumentException("'" +
customer.getCreditLimit() +
" is not enough credit for a '" + newBalance
+ " purchase.");
Update balance
and persist
If a request is made to charge a customer's account, the customer manager will first
try to retrieve the customer record from the database. If the customer can't be found,
the manager will—trustingly—set up a new credit account for that customer. The cus-
tomer manager will then try to charge the customer's account. If the customer's credit
limit is exceeded, no charge will be made and an exception will be thrown.
Not only will nothing be charged to the account, no changes at all will be made. In
particular, no account will be created for the new customer. Although the new cus-
tomer instance was created and persisted, the entire chargeToAccount method is
wrapped in a single transaction. If any exception is thrown from the method, all
changes made in the method will be rolled back.
You can update the food stock levels in a similar way in the inventory manager class:
public int removeStock(String name, int quantity) {
FoodImpl food = getFood(name);
int currentLevel = food.getQuantityInStock();
int newLevel = currentLevel - quantity;
if (newLevel >= 0) {
return newLevel;
} else {
throw new IllegalArgumentException(
"Cannot have level below 0: " + newLevel);
There should never be an attempt to purchase nonexistent food, so you don't add
special code to handle that case. You automatically created customer accounts for new
Search WWH ::

Custom Search