Classes, objects and access boundaries: keeping every object valid
Why bad data gets in when anyone can change a field: objects, constructors that enforce invariants, static as shared state, access modifiers as the size of a boundary, and how to review classes an AI wrote.
On this page
1. The problem
Class Order has a public int quantity field, and 23 places in the code assign to it directly. An import job sets quantity = -3; 41 orders with negative quantities reach invoices. There's no single place to check.
2. Key idea
An object bundles three things: state (fields), behaviour (methods) and identity (two orders with the same content are still two orders, which is why == differs from equals). A class is the template for creating objects with new.
The core idea: the object itself guards the rules that must always hold, called invariants ("quantity > 0"). Whether data is right depends on how many places can change it. Every extra place is one more place that can forget the check.
| Tool | Answers | Failure when misused |
|---|---|---|
| Constructor | is the object valid from birth? | half-built objects waiting for setters |
| Access modifier | how many places can read and write? | 23 assignments, none checked |
static |
per object or per class? | globals: data leaks across requests and tests |
| Package | which classes may know each other's details? | everything public "for convenience" |
2.1 How far to open?
Order of choice: private → package-private (no keyword) → protected → public. Opening up is always easy; narrowing something already public breaks other people's code.
| Choice | Use when | Don't use when |
|---|---|---|
private field + checking method |
default for all state | DTOs that only carry data (use record) |
| Package-private | details shared within one feature | things other modules call |
protected |
a deliberate extension point for subclasses | "so tests can reach it" |
public |
a contract you'll keep long-term | helper methods, fields |
Two things people forget: protected opens to the whole package, not only subclasses. And once you write any constructor, the compiler no longer adds the default constructor (JPA and Jackson need one).
3. In Java
public final class Order {
private static final AtomicInteger CREATED = new AtomicInteger(); // one copy for the class
private final String id; // per-object state
private int quantity;
public Order(String id, int quantity) { // valid from birth
if (quantity <= 0) throw new IllegalArgumentException("quantity must be > 0");
this.id = id; // this.id is the field, id the parameter
this.quantity = quantity;
CREATED.incrementAndGet();
}
public Order(String id) { this(id, 1); } // constructor chaining: checks live in one place
public void addItems(int more) { // state changes through behaviour, no setter
if (more <= 0) throw new IllegalArgumentException("more must be > 0");
quantity += more;
}
public int quantity() { return quantity; }
}
// new Order("o1", -3); // IllegalArgumentException: quantity must be > 0Other languages: Go uses upper/lower case to export and a NewOrder function instead of constructors; TypeScript has private (compile time) and #field (runtime); databases use CHECK constraints.
Packages, imports and the protected trap
- A package creates a namespace (
java.util.Datevsjava.sql.Date). Names are lowercase, reversed domain; the directory must match the package name.java.langis always imported. - Packaging by feature (
order,payment) lets many classes stay package-private; by layer (controller,service) forces everythingpublic. - A subclass in another package can read a
protectedfield throughthis, but not through a variable of the parent type:other.departmentfails with "has protected access". - Top-level classes can only be
publicor default. Since Java 9, apublicpackage that its module doesn'texportsis still unusable from other modules. void Order()is a regular method, not a constructor.
4. Working with AI
Delegate to AI: class skeletons, records for DTOs, tests for each invariant (boundaries, null).
Check yourself:
- No mutable
publicfields; every field that can befinalis. - The constructor checks invariants; no object is "valid after calling enough setters".
- State with rules (balance, order status) has no setter.
- No mutable
staticin Spring beans:grep -n "static [^f].*=" src/main. - A no-arg constructor exists only when JPA/Jackson needs it, and is
protected.
5. Exercises
Exercise 1: Review a "simple cache"
AI's PR description: "The bean is a singleton so it's thread-safe, no need for Redis". Find the bugs, name a test, fix it.
@Service
public class CartService {
private static final Map<String, Cart> CARTS = new HashMap<>();
public Cart cartOf(String userId) {
return CARTS.computeIfAbsent(userId, id -> new Cart());
}
}Solution to Exercise 1
- Singleton doesn't mean thread-safe. One bean serves many requests in parallel; a concurrently modified
HashMaploses entries or breaks. Test: 16 threads callcartOfwith 10,000 users, checkCARTS.size(). staticoutlives the bean: two Spring contexts in the same test JVM share the map.- Unbounded: nothing is ever removed, the heap grows to
OutOfMemoryError. - 3 pods means 3 maps; a request landing on another pod loses the cart.
- Fix: a cart is business data, store it in Redis or the DB. For a local cache, use an instance field with Caffeine, bounded and with a TTL.
Exercise 2: Choose between two designs
(A) Order has setStatus(Status), and OrderService checks "only ship after payment". (B) Order has pay() and ship(), no setter; ship() throws if not paid. Pick one; when is the other reasonable?
Solution to Exercise 2
Pick B: the rule lives in one place, and every caller (service, job, admin tool, AI-written code later) must go through it. With A, every new setStatus call is one more place that can skip the check, exactly the 23 assignments from section 1.
A is fine when the object is just a DTO carrying data across a boundary with no rules; then a record beats setters.
Summary
- Object = state + behaviour + identity; a class is the template.
- Constructors check invariants; objects are valid from birth.
- Start from
private, open only with a reason. - Mutable
staticis a disguised global. protectedopens to the whole package.
Comments
Community rules