...
To achieve a better handling of both correct and incorrect results, a combination of the two previous approaches should be used. Be aware to differentiate between cases when an error value should be returned instead of an exception and vice versa.
Noncompliant code example
As shown in this example, methods that are subject to fail could compromise the state of the object if they do not return a value that the developer can interpret.
Code Block | ||
---|---|---|
| ||
public void updateNode(int id, int newValue){ Node current = root; while(current != null){ if(current.getId() == id){ current.setValue(newValue); break; } current = current.next; } } |
Compliant solution
A recommended solution for this example could be to return the result of the operation. The method could return true
if it was successful and false
if it wasn't.
Code Block | ||
---|---|---|
| ||
public boolean updateNode(int id, int newValue){ Node current = root; while(current != null){ if(current.getId() == id){ current.setValue(newValue); return true; } current = current.next; } return false; } |
Compliant solution
Another solution that could provide more information could return the updated Node
so the developer could verify the new state of the object and null
if the operation did not succeed. Appropriate return values for methods could vary depending on the different paths that the implementation can follow or on the information that the developer finds more useful.
Code Block | ||
---|---|---|
| ||
public Node updateNode(int id, int newValue){ Node current = root; while(current != null){ if(current.getId() == id){ current.setValue(newValue); return current; } current = current.next; } return null; } |
Compliant solution
This solution provides a combination of both approaches mentioned. In this case, an exception is thrown if the operation was not successful.
Code Block | ||
---|---|---|
| ||
public Node updateNode(int id, int newValue) throws IdNotFoundException { Node current = root; while(current != null){ if(current.getId() == id){ current.setValue(newValue); return current; } current = current.next; } throw new IdNotFoundException(); } |
Risk assesment
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MET04-J | medium | unlikely | medium | P4 | L3 |
References
Wiki Markup |
---|
\[[Ware 08|AA. Java References#Ware 08]\] |