Banking Service class BankingService { LinkedList accounts; LinkedList customers; double getBalance(int forAcctNum) { for (Account acct:accounts) { if (acct.number == forAcctNum) return acct.balance; } return 0; } double withdraw(int forAcctNum, double amt) { for (Account acct:accounts) { if (acct.number == forAcctNum) { acct.balance = acct.balance - amt; return amt; } return 0; } String login(String custname, int withPwd) { for (Customer cust:customers) { if (cust.name.equals(custname)) { if (cust.password == withPwd) return "Welcome"; else return "Try Again"; }} return "Oops -- don't know this customer"; } class Customer { String name; int password; LinkedList accounts; } class Account { int number; Customer owner; double balance; }
Problems With Code “if (cust.password == withPwd)” Should not be allowed BankingService shouldn’t be doing math regarding withdrawals, put that in Account class Relies on a linkedlist of customers and linkedlist of accounts, which spills into getBalance, withdraw, and login methods “return 0;” Is this an error or the actual balance? It could be either. These should be separated.
Problems With Code: Encapsulation “if (cust.password == withPwd)” Should not be allowed BankingService shouldn’t be doing math regarding withdrawals, put that in Account class Relies on a linkedlist of customers and linkedlist of accounts, which spills into getBalance, withdraw, and login methods “return 0;” Is this an error or the actual balance? It could be either. These should be separated.
Problems With Code: Exceptions “return 0;” Is this an error or the actual balance? It could be either. These should be separated.
Getters.getBalance() returns balance field Not directly accessing the field in another class
Access Modifiers Private: item is only accessible by name inside the class. To access field outside classes, need getter Public: every other class or object can access item Protected: objects in current class and all of its subclasses (and their subclasses) can access this item “Generally we want to make all of the fields in all of the classes private. This is a good general rule of thumb, unless you have a good reason to do otherwise.”
More Good Programming Practices Put access modifiers on every field and method (including constructors) in a class. Any method that is visible through an interface must be public. Any method that another class must use should be public. Make constructors in abstract classes protected, so subclasses can invoke them. Make constructors that can’t be used by other classes private.