javaabstract-classassertabstract-methods

Checking abstract method behavior (the contract) with assertions in Java


I want the abstract method to be implemented to keep some contract e.g.

I have a Cells abstract class which is a wrapper around Cell[], Cells abstract class has abstract protected method _initCells, and I declared initCells final and public method that uses assertions to check if in the Cell[] from _initCells method output doesn't contain duplicates and out-of-bounds cells regardless of whether it is chess cells or checker cells.

But assertions are disabled by default and if another package wants to create sub-classes of Cells the programmer can ignore the contract by not enabling the assertions.

and what if I have a interface instead of abstract class, how can I enforce a contract?

So far I decided to print a message in System.err and call System.exit from initCells method.


Solution

  • Assertions are disabled by default, but exceptions aren't. If this precondition is a major footgun or is likely to cause safety or security issues if not followed, then raise RuntimeException or one of its subclasses when you detect nonconformance.

    public final initCells() {
      _initCells();
      if (containsDuplicates()) {
        throw new RuntimeException("Cells contain duplicates");
      }
      if (anyCellIsOutOfBounds()) {
        throw new RuntimeException("Cell is out of bounds");
      }
    }