Preventing Assertions from Breaking Code
The purpose of assertions is generally to find bugs when testing software. However, if the assertions themselves break code, then it becomes problematic. For example, a transient network error or a timing issue on a system can cause an assertion to fail. Additionally, if we use assertions to validate inputs on public methods, we run the risk of leaving our system unprotected against invalid and malicious inputs.
One way to circumvent the negative impact of assertions is to use them judiciously. Use assertions only for things that should never happen in a well-designed system.
public class AssertionsLab {
public static void main(String[] args) {
double result = squareRoot(4);
System.out.println("Square root: " + result);
double negativeNumber = -4;
result = squareRoot(negativeNumber);
System.out.println("Square root: " + result);
}
public static double squareRoot(double number) {
assert number >= 0 : "Number should be non-negative";
return Math.sqrt(number);
}
}