CSE Roadmap

Core tier · about 2 hours · 7 parts

Part 3 of 7 · 1 min read

The lowest access level

Start private, open up only when needed.

EJ gives a simple rule: give every class and member the narrowest access that still lets the software work.

Java has four levels for members: - private: only inside the class where it is declared. - package-private (no modifier): any class in the same package. - protected: subclasses, and the same package. - public: everywhere.

For a top-level class, only package-private and public exist. EJ's advice: if a class can be package-private, make it so. A public class is part of the exported API, and the author must support it forever. A package-private class is part of the implementation and can be changed or removed later.

A made-up cost count. A class has 10 public methods and 2 clients each use 3. Seven methods are used by nobody, yet all ten are now a promise. Making those seven package-private removes the promise.

Check yourself: 1. What is the default access level in Java? 2. Why is a public class a long-term promise? 3. Which level should a new field start at?