...
It if often assumed that private
methods do not require any validation because they are not directly accessible from code present outside the class. This assumption is misleading as programming errors often arise due to legit code misbehaving in unanticipated ways. For example, a tainted value may propagate from a public API to one of the internal methods via its parameters.
Wiki Markup |
---|
Assertions should not be used to validate parameters of {{public}} methods. According to the Java Language Specification \[[JLS 05|AA. Java References#JLS 05]\]: |
Along similar lines, assertions should not be used for argument-checking in
public
methods. Argument-checking is typically part of the contract of a method, and this contract must be upheld whether assertions are enabled or disabled.Another problem with using assertions for argument checking is that erroneous arguments should result in an appropriate runtime exception (such as IllegalArgumentException, IndexOutOfBoundsException or NullPointerException). An assertion failure will not throw an appropriate exception. Again, it is not illegal to use assertions for argument checking on public methods, but it is generally inappropriate.
...
This noncompliant code example uses assertions to validate arguments of a public
method.
Code Block | ||
---|---|---|
| ||
public static int AbsAdd(int x, int y) { assert x != Integer.MIN_VALUE; assert y != Integer.MIN_VALUE; assert ((x <= Integer.MAX_VALUE - y)); assert ((x >= Integer.MIN_VALUE - y)); return Math.abs(x) + Math.abs(y); } |
...