assert condition : message;
on if (!condition) throw new AssertionError(message);
- == false true
, but to maintain some test state inside the class and check it in the methods. With the help of the trick with assert
you can achieve this almost for free when performing with disabled checks.void
), and the code is boolean
and always true
. These methods are called "via" assert
. That is, when checks for a class are disabled, methods are not called, the check state is not initialized and is not updated, and only one null
reference in the object’s memory remains in the overhead. import java.util.HashSet; import java.util.Set; public final class MyCoolSet<E> { private Object[] coolStorage; private transient Set<E> referenceSet; public MyCoolSet() { // ... init cool storage assert initReferenceSet(); } private boolean initReferenceSet() { referenceSet = new HashSet<>(); return true; } public int size() { // return the cool size return 42; } public boolean add(E e) { // .. add an element to the cool storage boolean added = true; assert addToReferenceSet(e); return added; } private boolean addToReferenceSet(E e) { referenceSet.add(e); checkSize(); return true; } private void checkSize() { assert referenceSet.size() == size() : "Cool size diverged from reference size"; } public boolean remove(Object o) { // ... remove an element from the cool storage boolean removed = true; assert removeFromReferenceSet(o); return removed; } private boolean removeFromReferenceSet(Object o) { referenceSet.remove(o); checkSize(); return true; } }
Source: https://habr.com/ru/post/247253/
All Articles