Access Modifiers and Encapsulation Banking Service class Banking

Access Modifiers and Encapsulation

Banking Service class Banking. Service { Linked. List<Account> accounts; Linked. List<Customer> customers; double get. Balance(int for. Acct. Num) { for (Account acct: accounts) { if (acct. number == for. Acct. Num) return acct. balance; } return 0; } double withdraw(int for. Acct. Num, double amt) { for (Account acct: accounts) { if (acct. number == for. Acct. Num) { acct. balance = acct. balance - amt; return amt; } } return 0; } String login(String custname, int with. Pwd) { for (Customer cust: customers) { if (cust. name. equals(custname)) { if (cust. password == with. Pwd) return "Welcome"; else return "Try Again"; }} return "Oops -- don't know this customer"; } } class Customer { String name; int password; Linked. List<Account> accounts; } class Account { int number; Customer owner; double balance; }

Problems With Code �“if (cust. password == with. Pwd)” �Should not be allowed �Banking. Service 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 get. Balance, 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 == with. Pwd)” �Should not be allowed �Banking. Service 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 get. Balance, 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 �. get. Balance() 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.
- Slides: 8