📜 ⬆️ ⬇️

Java Check State

The assert keyword (validation) appeared in Java 1.4. It seems to me that many still try to avoid it, or wrap it in utility static methods with the ability to quickly change assert condition : message; on
 if (!condition) throw new AssertionError(message); 

throughout the code. Someone is afraid that the checks are not reliable enough, and if someone forgets to turn them on, some bugs will go unnoticed. Someone, on the contrary, maniacally thinks about performance: if someone turns on checks for the subsystem / library written by the guys from the first group and forgets to exclude packages or classes of the “productive” library, execution will be slowed down by useless calculations.

Although, in my opinion, there is nothing terrible about checks, they can and should be arranged in the code as generously as possible. First, as I mentioned (but for some it may be new), checks can be flexibly configured ( enabled / disabled in packages and individual classes ) either from the command line when launching the JVM or programmatically (via ClassLoader) , so if you suddenly want to turn on checks in one system and turn off - in another, this is certainly a solvable problem.

Secondly, sometimes you want to check not trivial conditions like - == 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.

The trick is simple: the initialization and update of the check state are put into methods that do not return anything ( 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.
')
Example:
 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