1 / 8

Accessibility & Mutability

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.

plucille
Download Presentation

Accessibility & Mutability

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Accessibility & Mutability

  2. Minimize Class/Method accessibility • Hide implementation. private List list = new LinkedList(); public List getList() { return list; }

  3. 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.

  4. 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.

  5. 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 

  6. 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.

  7. 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.

  8. Example • PhoneNumber.java • Shared.java

More Related