80 likes | 93 Views
Accessibility & Mutability. Minimize Class/Method accessibility. Hide implementation. private List list = new LinkedList(); public List getList() { return list; }. Minimize Class/Method accessibility. Each class/member is as in accessible as possible.
E N D
Minimize Class/Method accessibility • Hide implementation. private List list = new LinkedList(); public List getList() { return list; }
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.
public package protected private Accessibility • protected members are • accessible to subclasses • outside package. • protected members are • part of a class’s API! • Prefer package-private.
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
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.
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.
Example • PhoneNumber.java • Shared.java