Lack of concern about leaving objects in an inconsistent state upon when exceptional conditions may spring up a gaping hole of exploitable vulnerabilities in them. Techniques that are typically employed to avoid this scenario arearise may leave them vulnerable. Usual techniques for avoiding this scenario 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 does
- 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
...
This noncompliant code example shows a Dimensions
class that contains three internal attributes, the length
, width
and height
of a rectangular box. The getVolumePackage()
method is designed to return the total volume required to hold the box, after accounting for packing packaging material which adds a further 2 units to the dimensions of each side. Non negative positive values are rejected in during the subsequent input validation. Also, the weight
of the object is passed in as a parameter and cannot be more than 20 units. Consider the case where the weight
is more than 20 units (21 units, here). This will cause causes an IllegalArgumentException
which will be is intercepted by the custom error reporter. While the logic restores the object's original state in the absence of this exception, it omits doing the same from within the catch
block. This violates the object's invariants and such that when getVolumePackage()
is called for the second time, it produces incorrect results.
...
Code Block | ||
---|---|---|
| ||
// ... } catch(Throwable t) { MyExceptionReporter mer = new MyExceptionReporter(); mer.report(t); // sanitize length -=2; width -= 2; height -= 2; // revert back return -1; } |
Compliant Solution
Another A more preferable way is to perform input validation before modifying the state of the object.
...