Invariants.java

  1. package com.renomad.minum.utils;

  2. /**
  3.  * Utilities for asserting invariants within the code.
  4.  * <br>
  5.  * The purpose here is to make firm statements about the code.  This is
  6.  * to help document the code, (e.g. at this point, x is the sum of the ...),
  7.  * to include testing mindset in the code, and to guard against adding
  8.  * bugs during maintenance.
  9.  */
  10. public final class Invariants {

  11.     private Invariants() {
  12.         // cannot construct
  13.     }

  14.     /**
  15.      * Specify something which must be true.
  16.      * <p>
  17.      * Throws an {@link InvariantException} if false
  18.      * @param predicate the boolean expression that must be true at this point
  19.      * @param message a message that will be included in the exception if this is false
  20.      */
  21.     public static void mustBeTrue(boolean predicate, String message) {
  22.         if (!predicate) {
  23.             throw new InvariantException(message);
  24.         }
  25.     }

  26.     /**
  27.      * Specify something which must be false
  28.      * <p>
  29.      * Throws an {@link InvariantException} if true
  30.      * @param predicate the boolean expression that must be false at this point
  31.      * @param message a message that will be included in the exception if this is true
  32.      */
  33.     public static void mustBeFalse(boolean predicate, String message) {
  34.         if (predicate) {
  35.             throw new InvariantException(message);
  36.         }
  37.     }

  38.     /**
  39.      * specifies that the parameter must be not null.
  40.      * <p>
  41.      * Throws an {@link InvariantException} if null.
  42.      * @return the object if not null
  43.      */
  44.     public static <T> T mustNotBeNull(T object) {
  45.         if (object == null) {
  46.             throw new InvariantException("value must not be null");
  47.         } else {
  48.             return object;
  49.         }
  50.     }
  51. }