Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Added an Android Implementation Details section

...

The method getAbsAdd() computes and returns the sum of the absolute value of parameters x and y. It lacks argument validation, in violation of rule MET00-J. Validate method arguments. Consequently, it can produce incorrect results because of integer overflow or when either or both of its arguments are Integer.MIN_VALUE.

Code Block
bgColor#FFcccc

public static int getAbsAdd(int x, int y) {
  return Math.abs(x) + Math.abs(y);
}
getAbsAdd(Integer.MIN_VALUE, 1);

...

This noncompliant code example uses assertions to validate arguments of a public method.

Code Block
bgColor#FFcccc

public static int getAbsAdd(int x, int y) {
  assert x != Integer.MIN_VALUE;
  assert y != Integer.MIN_VALUE;
  int absX = Math.abs(x);
  int absY = Math.abs(y);
  assert (absX <= Integer.MAX_VALUE - absY);
  return absX + absY;
}

...

This compliant solution validates the method arguments by ensuring that values passed to Math.abs() exclude Integer.MIN_VALUE and also by checking for integer overflow.

Code Block
bgColor#ccccff

public static int getAbsAdd(int x, int y) {
  if (x == Integer.MIN_VALUE || y == Integer.MIN_VALUE) {
    throw new IllegalArgumentException();
  }
  int absX = Math.abs(x);
  int absY = Math.abs(y);
  if (absX > Integer.MAX_VALUE - absY) {
    throw new IllegalArgumentException();
  }
  return absX + absY;
}

...

MITRE CWE

CWE-617. Reachable assertion

Android Implementation Details

The assert statement is supported on the Dalvik VM but is ignored under the default configuration. Assertions may be enabled by setting the system property "debug.assert" via: adb shell setprop debug.assert 1 or by sending the command line argument "--enable-assert" to the Dalvik VM.

Bibliography

[Daconta 2003]

Item 7. My assertions are not gratuitous

[ESA 2005]

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

[JLS 2005]

§14.10, The assert Statement

 

      05. Methods (MET)