Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by NavBot

...

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 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.

...

Code Block
bgColor#FFcccc
public static int AbsAdd(int x, int y) {
  assert x != Integer.MIN_VALUE;
  assert y != Integer.MIN_VALUE;
  assert ((x &lt;<= Integer.MAX_VALUE - y));
  assert ((x &gt;>= Integer.MIN_VALUE - y));
  return Math.abs(x) + Math.abs(y);
}

...

Code Block
bgColor#ccccff
public static int AbsAdd(int x, int y) {
  if((x == Integer.MIN_VALUE || y == Integer.MIN_VALUE) ||
    (x&gt;0x>0 &amp;&amp; y&gt;0y>0 &amp;&amp; (x &gt;> Integer.MAX_VALUE - y)) || 
    (x&lt;0x<0 &amp;&amp; y&lt;0y<0 &amp;&amp; (x &lt;< Integer.MIN_VALUE - y)))
      throw new IllegalArgumentException();
  return Math.abs(x) + Math.abs(y);
}

...

MET04-J. Always provide feedback about the resulting value of a method&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;      12. Methods (MET)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;MET30-J. Follow the general contract while overriding the equals method      MET06-J. Methods that perform a security check must be declared private or final