Coding Techniques
Access Modifiers and Packages · Study material
Expose a minimal public API
Start every member as private and widen it only when another class truly needs it. Return read-only views of internal collections.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
// A class exposes a small public API and hides everything else
static final class Playlist {
private final List<String> songs = new ArrayList<>(); // private state
private static final int MAX = 3; // private constant
public boolean add(String song) { // public operations
if (songs.size() >= MAX || songs.contains(song)) return false;
songs.add(normalise(song));
return true;
}
public List<String> songs() { return Collections.unmodifiableList(songs); } // read-only view
private static String normalise(String s) { return s.strip(); } // private helper
}
public static void main(String[] args) {
Playlist p = new Playlist();
System.out.println(p.add(" Kesariya ") + " " + p.add("Naatu Naatu") + " " + p.add("Jai Ho") + " " + p.add("Extra"));
try {
p.songs().add("Hacked");
} catch (UnsupportedOperationException e) {
System.out.println("read-only: " + p.songs());
}
}
}
true true true false read-only: [Kesariya, Naatu Naatu, Jai Ho]
Organising packages by feature
// ✔ package by feature – related classes stay together and can use package-private access
com.learnfrenzy.orders Order, OrderService, OrderRepository, OrderValidator (package-private)
com.learnfrenzy.payments Payment, PaymentGateway, RazorpayGateway (package-private)
com.learnfrenzy.users User, UserService
// ✘ package by layer – everything must be public to talk across packages
com.learnfrenzy.controllers / services / repositories / models Resolving name conflicts
import java.util.List; // the one you use most gets the short name
import java.util.Date;
class Report {
List<String> lines; // java.util.List
java.awt.List widget; // fully qualified: the AWT component
Date created; // java.util.Date
java.sql.Date sqlDate; // fully qualified
}
// Single-type imports beat wildcard imports, and a class in the same file or package
// beats a wildcard import with the same simple name. Access modifier checklist
- Fields: private (constants may be public static final).
- Helper methods: private.
- Methods for subclasses to customise: protected.
- Classes used only inside a feature package: package-private.
- Public API: public, documented and kept small.
- Use reverse-domain, lower-case package names.
- In libraries, export only API packages from module-info.java.