Daily tip #12
Tip of the day #12
Don’t use assertions.
I know that assert obj != null
is a lot shorter than if (obj == null) { throw new IllegalArgumentException("object was null"); }
,
but by default, assertions are disabled at runtime.
History
Assertions were added to the Java language in JDK 1.4. They were intended to be used as a debugging aid, not as a mechanism for handling run-time errors. The idea was that you could use them to document your assumptions about the behavior of your program, and they would be automatically verified at runtime.
Although assertions are still in the language, they are now discouraged from use. It can reduce boilerplate, but it can also hide bugs.
public class BugExample {
public static void main(String[] args) {
int accountBalance = 100;
int withdrawalAmount = 150;
// Misusing assertion to hide a bug
assert accountBalance >= withdrawalAmount : "Insufficient funds!";
// Perform the withdrawal
accountBalance -= withdrawalAmount;
System.out.println("Withdrawal successful. Remaining balance: " + accountBalance);
}
}
If you run this program with assertions enabled, you will see the following output:
Exception in thread "main" java.lang.AssertionError: Insufficient funds!
at BugExample.main(BugExample.java:7)
but if you run it with assertions disabled, you will see the following output:
Withdrawal successful. Remaining balance: -50
Assertions are not meant to hide bugs but to help you identify and fix them during development and testing. In real-world applications, it’s better to handle such situations with proper error handling and validation rather than relying on assertions to suppress errors.
Conclusion
There is not a repo for this item, since we should not use assertions. =D If you want to check, just copy the code above and run it with assertions enabled and disabled.