Sub topic 5
Choosing a Class's Public API
A class often needs to hide some details while giving other code a useful way to work with it. Its public API is that outward-facing part.
An API, or application programming interface, is the set of features that other code can use, along with the promises about how those features behave. For a Java class, the public API can include its public constructors, methods, and fields.
A caller is code that uses an API. A caller should not need to know every detail inside a class. It should only need to know what the class offers and what to expect.
In this chapter, you will design an API for counting reserved seats. The goal is not to expose every piece of data. It is to offer the operations a caller needs.
Start with what callers need to do
Imagine a small program that tracks seats for one event. Other parts of the program need to:
- Create a counter with a fixed number of seats.
- Find out how many seats are reserved or available.
- Try to reserve a number of seats.
They do not need to set the number of reserved seats to any value they choose. If they could do that, they might set it above the event's capacity.
This gives us a useful design question: what should callers be able to ask the class to do?
A method named tryReserve can express the task more clearly than a method named setReserved. The first asks the class to perform an operation. The second asks it to replace a number, without saying why.
The class will also answer questions through methods such as getAvailable. A method that returns a value without changing the object is often called a query. A method that asks an object to perform a task is an operation.
Decide what is public
An access modifier is a Java keyword that controls where a class or member can be used. A member is a field or method declared inside a class.
- public makes a member available to callers that can access its class.
- private keeps a member out of the public API. Other classes cannot access it directly in ordinary Java code.
A public class is not required to make all its members public. In fact, a class can make its useful operations public while keeping its fields private.
Encapsulation is the practice of keeping an object's data and the behavior that works with it together, while controlling how callers use them. Access modifiers help with this, but they are not the whole design. A good API must also provide operations that make sense.
The following diagram shows the boundary we want.
Build a small seat counter
The counter will have this rule: the number of reserved seats must stay between zero and the event's capacity. A rule that must remain true for an object is called an invariant.
The public API will let callers try a reservation. If enough seats are available, the reservation succeeds. Otherwise, it fails without changing the count.
Write the class
Save this file as SeatCounter.java:
public class SeatCounter {
private final int capacity;
private int reserved;
public SeatCounter(int capacity) {
if (capacity < 1) {
throw new IllegalArgumentException("Capacity must be positive");
}
this.capacity = capacity;
this.reserved = 0;
}
public int getCapacity() {
return capacity;
}
public int getReserved() {
return reserved;
}
public int getAvailable() {
return capacity - reserved;
}
public boolean tryReserve(int seats) {
if (seats < 1) {
throw new IllegalArgumentException("Seats must be positive");
}
if (seats > capacity - reserved) {
return false;
}
reserved += seats;
return true;
}
}The fields are private, so a caller cannot write to them directly. The final keyword on capacity means that the field cannot be assigned again after it is set. The reserved field can change when a reservation succeeds.
The constructor is public. A constructor is the part of a class used to create an object. Here, callers supply the event capacity when they create a SeatCounter.
An exception is a signal that an operation could not proceed normally. The constructor throws an IllegalArgumentException when the supplied capacity is less than one. The tryReserve method throws the same kind of exception when the requested number of seats is less than one.
The method tryReserve returns a boolean. A boolean is a value that is either true or false. Here, true means the seats were reserved. False means there were not enough seats available.
Call the API
Save this second file as SeatCounterDemo.java in the same folder:
public class SeatCounterDemo {
public static void main(String[] args) {
SeatCounter counter = new SeatCounter(5);
System.out.println("Capacity: " + counter.getCapacity());
System.out.println("Reserve 2: " + counter.tryReserve(2));
System.out.println("Reserve 4: " + counter.tryReserve(4));
System.out.println("Reserved: " + counter.getReserved());
System.out.println("Available: " + counter.getAvailable());
try {
counter.tryReserve(0);
} catch (IllegalArgumentException error) {
System.out.println("Invalid request: " + error.getMessage());
}
}
}With a Java development kit installed, open a terminal in that folder and run:
javac SeatCounter.java SeatCounterDemo.java
java SeatCounterDemoThe program prints:
Capacity: 5
Reserve 2: true
Reserve 4: false
Reserved: 2
Available: 3
Invalid request: Seats must be positiveThe first request succeeds. The second asks for four seats when only three remain, so it returns false. The count stays at two. The final request is invalid because it asks for zero seats, so the method throws an exception that the demo catches.
Read the API as a set of promises
An API contract is the set of expectations a caller can rely on. It describes what inputs mean, what results mean, and what happens when an operation cannot proceed.
For SeatCounter, the contract includes these promises:
| Public feature | Promise to the caller |
|---|---|
| SeatCounter(int capacity) | Creates a counter with no reserved seats. Capacity must be positive. |
| getCapacity() | Returns the fixed total number of seats. |
| getReserved() | Returns the current number of reserved seats. |
| getAvailable() | Returns the number of seats not yet reserved. |
| tryReserve(int seats) | Reserves the requested seats and returns true if they are available. Returns false without changing the count if they are not available. A request below one throws an exception. |
The difference between false and an exception is part of the design. A request for more seats than remain is a normal possibility. A request for zero or fewer seats does not make sense for this operation.
A parameter is a named input in a method or constructor declaration. In tryReserve, seats is a parameter. When the demo calls tryReserve(2), the value 2 is the argument: the value passed to that parameter.
A method signature is its name and the types of its parameters. For example, tryReserve(int) identifies the method by name and input type. The return type and behavior are also important parts of the API contract, even though Java does not include the return type in the method signature.
Prefer useful operations over direct writes
Suppose reserved were a public field. A caller could assign it a number larger than capacity. The class would no longer have a dependable way to keep its seat-count rule.
The private field and public method divide the work more clearly:
- The caller says how many seats it wants.
- SeatCounter checks the request.
- SeatCounter reports the result.
The caller does not have to repeat the check each time. It also does not need to know how the class stores the count.
This does not mean every field needs a public getter and setter. A getter is a method that returns a value. A setter is a method that assigns a value. Both are choices, not requirements.
The three getters in the example answer questions our callers need. A setReserved method would let callers replace the count without explaining what happened. Since that is not a task our callers need, we leave it out.
Likewise, there is no setCapacity method. The example treats capacity as fixed once the counter is created. If a later version needs to support changing an event's capacity, that feature should have a clear rule for what happens when seats are already reserved.
A class with private fields can still be changed through its public methods. SeatCounter is not unchangeable: tryReserve can change the reserved count. The point is that the class controls how that change happens.
Keep the API focused
A small API can be easier to learn and harder to misuse. That does not mean making everything private. If callers cannot perform their real tasks, the class is not useful.
For each proposed public feature, ask:
- What task or question does this support?
- What does the caller need to provide?
- What result will the caller get?
- What happens when the request cannot be completed?
- Does the caller need this feature, or is it an internal detail?
In the example, callers need to know whether a reservation worked. Returning a boolean answers that question. Callers do not need a public method that performs only one small step of the reservation check.
The implementation is the code inside a class that carries out its work. Private fields and internal steps are implementation details. The public API describes what callers can ask for and what they can expect.
Keeping those details private gives the class author room to change them. For example, the author could change how a count is calculated, provided the public methods still keep their documented promises.
There is a trade-off. Adding a public feature can make a class more convenient, but it also creates another promise to maintain. A public getter, for example, may seem small, but callers can come to depend on the value it returns.
Think before changing a public API
Once other code uses a public method, changing or removing it can cause problems. If getAvailable is removed, code that calls it will no longer compile. Compiling is the process of translating Java source code into a form the Java runtime can execute.
A change can also cause trouble without causing a compile error. For example, changing tryReserve so that it returns true even when no seats were reserved would break its meaning for existing callers.
Before changing a public feature, consider both questions:
- Will existing calls still compile?
- Will those calls still behave as callers expect?
The example also has limits worth stating. It only counts seats; it does not record who reserved them or assign seat numbers. It is intended for one task at a time. If several tasks try to reserve seats at the same time, this version does not promise correct results.
Clear limits are part of a useful API. They help callers decide whether the class is right for their task.
Practice
Exercise
Why does SeatCounter offer tryReserve instead of a public reserved field?
Show answer
tryReserve expresses the caller's task and lets the class check whether seats are available before changing the count. A public field could be assigned an invalid count.
Exercise
A SeatCounter has capacity 5 and 2 reserved seats. What does tryReserve(4) return, and how many seats remain reserved?
Show answer
It returns false because only 3 seats are available. The reserved count remains 2.
Exercise
If tryReserve is changed to return true when a request fails, why is that an API problem even if callers still compile?
Show answer
It breaks the promised meaning of the return value. Callers may believe seats were reserved when they were not.