package com.cp.exercise.atm;
import java.util.HashMap;
import java.util.Map;
import com.cp.exercise.atm.exception.InsufficientBalanceException;
import com.cp.exercise.atm.exception.InvalidAccountExcetion;
import com.cp.exercise.atm.exception.InvalidDenominationException;
import com.cp.exercise.atm.exception.InvalidUserAccountExcetion;
public class ATMClient {
private static ATMClient client;
private ATMClient() {
}
public static ATMClient instanceOf() {
if(client == null) {
client = new ATMClient();
} return client;
}
private final Map
public synchronized void filledUserAccountWithInitialBalance(UserAccount userAccount, int initialBalance) {
validateAccount(userAccount);
userToAvailableBalance.put(userAccount, initialBalance);
}
public synchronized Integer checkBalance(UserAccount userAccount) {
return getBalance(userAccount);
}
public synchronized Map
userHaveEnoughMoney(userAccount, withDrawAmount);
denominationIsCorrect(withDrawAmount);
reAdjustAccountBalance(userAccount, withDrawAmount);
return getTotalNotesForThisAmount(withDrawAmount);
}
private Integer getBalance(UserAccount userAccount) {
if(userToAvailableBalance.containsKey(userAccount)) {
return userToAvailableBalance.get(userAccount);
}
throw new InvalidUserAccountExcetion(String.format("Account [%s] does not exist.", userAccount));
}
private void validateAccount(UserAccount userAccount) {
if(!userAccount.isValidAccount()) {
throw new InvalidAccountExcetion(String.format("Account [%s] is not valid", userAccount));
}
}
private void reAdjustAccountBalance(UserAccount userAccount, int withDrawAmount) {
final int balance = getBalance(userAccount) - withDrawAmount;
userToAvailableBalance.put(userAccount, balance);
}
private Map
return Denomination.totalNoOfNotes(withDrawAmount);
}
private void denominationIsCorrect(int withDrawAmount) {
if(!Denomination.isCorrect(withDrawAmount)) {
throw new InvalidDenominationException(String.format("This amount [%s] is not valid. Please enter multilier of [%s]", withDrawAmount,Denomination.names()));
}
}
private void userHaveEnoughMoney(UserAccount userAccount, int withDrawAmount) {
if(getBalance(userAccount) <> getBalance(userAccount)) {
throw new InsufficientBalanceException(String.format("Account [%s] has insufficient balance [%s].Requested amount [%s]",
userAccount, getBalance(userAccount), withDrawAmount));
}
}
}
No comments:
Post a Comment