bhylu.com

Advertisements

Java Keep a Domain Rule Behind Its Methods

Encapsulation lets a class control how its state changes. A getter-and-setter pair is not automatically a good design if the setter permits states the class is meant to prevent.

Understand the idea

Make fields private when callers should not bypass a rule. Expose an operation such as reserve rather than a generic updateCount if the operation carries a meaningful contract. Validate the proposed new state before assigning it, so a failed operation does not leave the object partially changed. Returning a mutable internal collection can also break encapsulation even when the field itself is private.

Run it locally

Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.

JDK and terminal setup

javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out Main

A worked example

Java 21+ · Main.java

public class Main {
    static class SeatPool {
        private final int capacity;
        private int booked;
        SeatPool(int capacity) {
            if (capacity < 0) throw new IllegalArgumentException("negative capacity");
            this.capacity = capacity;
        }
        boolean reserve(int seats) {
            if (seats <= 0) throw new IllegalArgumentException("positive seats required");
            if (seats > capacity - booked) return false;
            booked += seats;
            return true;
        }
        int remaining() { return capacity - booked; }
    }

    public static void main(String[] args) {
        SeatPool pool = new SeatPool(9);
        System.out.println(pool.reserve(4));
        System.out.println(pool.reserve(6));
        System.out.println(pool.remaining());
    }
}

Expected output

true
false
5

The first reservation changes booked to four. The second asks for more than the five remaining seats and returns false without changing state. A caller can inspect availability but cannot assign booked directly. The method’s result distinguishes insufficient capacity from an invalid non-positive request, which is rejected as bad input.

Check the official Java documentation for detailed contracts and supported options.