Accessibility Mutability Minimize ClassMethod accessibility Hide implementation private
Accessibility & Mutability
Minimize Class/Method accessibility • Hide implementation. private List list = new Linked. List(); public List get. List() { return list; } 2
Minimize Class/Method accessibility • Each class/member is as inaccessible as possible. • If a class can be package-private, don’t make it public. • If a class has only 1 client, make it a private nested class. • All methods not in the class’s API are private. • Attributes are private – Exception: Constants used by clients: public static final fields. E. g. , Color. green – Classes with public mutable fields are not thread-safe. 3
Accessibility public protected package • protected members are accessible to subclasses outside package. • protected members are part of a class’s API! • Prefer package-private. private 4
Mutability • An immutable object cannot be modified. They: – Are simple • They have exactly 1 state. • Class invariants satisfied when object is constructed, stay satisfied. – Are thread-safe – Can be shared freely Class should provide constants to encourage reuse. – Require a separate object for each distinct value 5
Minimize Mutability • If a class can be immutable, make it so. • If it cannot be immutable, minimize its mutability: – Minimize the # of mutable data members. – Minimize their mutability. 6
To Make A Class Immutable • Provide no mutators A mutator is a method that changes an object’s state. • Ensure that its methods cannot be overridden Typically done by declaring the class final • Make all fields final & private. • Recursively apply these rules to returned attributes. 7
Example • Phone. Number. java • Shared. java 8
- Slides: 8