...
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]\], section 14.10 ""The {{assert}} Statement"": |
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
orNullPointerException
). An assertion failure will not throw an appropriate exception. Again, it is not illegal to use assertions for argument checking onpublic
methods, but it is generally inappropriate.
...
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); } |
...
Code Block | ||
---|---|---|
| ||
public static int AbsAdd(int x, int y) { if((x == Integer.MIN_VALUE || y == Integer.MIN_VALUE) || (x>0x>0 && y>0amp; y>0 && (x >> Integer.MAX_VALUE - y)) || (x<0x<0 && y<0amp; y<0 && (x << Integer.MIN_VALUE - y))) throw new IllegalArgumentException(); return Math.abs(x) + Math.abs(y); } |
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
Wiki Markup |
---|
\[[JLS 05|AA. Java References#JLS 05]\] 14.10 The assert Statement \[[Bloch 08|AA. Java References#Bloch 08]\] Item 38: Check parameters for validity \[[ESA 05|AA. Java References#ESA 05]\] Rule 68: Explicitly check method parameters for validity, and throw an adequate exception in case they are not valid. Do not use the assert statement for this purpose \[[Daconta 03|AA. Java References#Daconta 03]\] Item 7: My Assertions Are Not Gratuitous |
...
MET04-J. Always provide feedback about the resulting value of a method 12. Methods (MET) MET30-J. Follow the general contract while overriding the equals method