Lack of concern about leaving objects Objects should not be left in an inconsistent state when exceptional conditions arise may leave them vulnerable. Usual techniques for avoiding this scenario maintaining object consistency include:
- Input validation (for example, method parameters)
- Reordering the logic so that the code capable of resulting in the exceptional condition, executes before the code that modifies the object executes
- Through the use of rollbacks, upon intercepting a failure notification
- Performing required operations on a temporary copy and committing changes to the original object, after their successful completion
...
A more preferable way is to perform input validation before modifying the state of the object. Also, statements that are incapable of throwing the exception should be moved outside the try
block.
Code Block | ||
---|---|---|
| ||
protected int getVolumePackage(int weight) { try { if(length <= 0 || width <= 0 || height <= 0 || weight <= 0 || weight > 20) throw new IllegalArgumentException(); // Validate first } catch(Throwable t) { MyExceptionReporter mer = new MyExceptionReporter(); mer.report(t); // Sanitize return -1; } length += 2; width += 2; height += 2; int volume = length * width * height; length -=2; width -= 2; height -= 2; return volume; } catch(Throwable t) { MyExceptionReporter mer = new MyExceptionReporter(); mer.report(t); // Sanitize return -1; } } |
Risk Assessment
Failing to restore prior object state on method failure can leave the object in an inconsistent state.
...