Java language
Java Class invariant
A design rule that every usable instance must preserve. Establish the rule in construction and check updates before mutation. This is a design convention, not a Java syntax feature.
Formal Syntax & Structure
java syntaxjava
if (units <= 0 || units > limit - used) return false;Working Example
Example Snippetjava
class Capacity { private final int limit; private int used; Capacity(int limit) { if (limit < 0) throw new IllegalArgumentException("negative limit"); this.limit = limit; } public boolean add(int units) { if (units <= 0 || units > limit - used) return false; used += units; return true; } public int remaining() { return limit - used; }}public class Main { public static void main(String[] args) { Capacity room = new Capacity(10); System.out.println(room.add(10)); System.out.println(room.remaining()); System.out.println(room.add(Integer.MAX_VALUE)); System.out.println(room.remaining()); }}