Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added int overflow check, made eg compilable, and defined use of wrappers

...

Code Block
bgColor#FFCCCC
public class Widget {
  public int total;
  void add() {
   (SomeType someParameter) {
     if (total < Integer.MAX_VALUE) {
      throw new ArithmeticException("Overflow");
    }
    total++;
    // ...
  }

  void remove() {  
   (SomeType someParameter if (total > Integer.MIN_VALUE) {
      throw new ArithmeticException("Overflow");
    }
    total--;
    // ...
  }
}

Compliant Solution

...

Code Block
bgColor#ccccff
public class Widget {
  private int total;
  void add() {
    if (someType someParametertotal < Integer.MAX_VALUE) {
      throw new ArithmeticException("Overflow");
    }
    total++;
    // ...
  }

  void remove() {
 (someType someParameter) {
       if (total > Integer.MIN_VALUE) {
      throw new ArithmeticException("Overflow");
    }

    total--;
    // ...
  }

  public int getTotal () {
    return total;
  }
}

It is good practice to use wrapper methods such as add(), remove() and getTotal, to manipulate private internal state because the methods can perform additional functions such as input validation and security manager checks prior to manipulating the state.

Noncompliant Code Example

...