Methods can return values to communicate failure or success or to update local objects or fields. Security risks can arise when method return values are ignored or when the invoking method fails to take suitable action. Consequently, programs must not ignore method return values.
When getter methods are named after an action, a programmer could fail to realize that a return value is expected. For example, the only purpose of the
ProcessBuilder.redirectErrorStream() method is to report via return value whether the process builder successfully merged standard error and standard output. The method that actually performs redirection of the error stream is the overloaded single-argument method
Noncompliant Code Example (File Deletion)
This noncompliant code example attempts to delete a file but fails to check whether the operation has succeeded:
This compliant solution checks the Boolean value returned by the
delete() method and handles any resulting errors:
Noncompliant Code Example (String Replacement)
This noncompliant code example ignores the return value of the
String.replace() method, failing to update the original string. The
String.replace() method cannot modify the state of the
String objects are immutable); rather, it returns a reference to a new
String object containing the modified string.
It is especially important to process the return values of immutable object methods. Although many methods of mutable objects operate by changing some internal state of the object, methods of immutable objects cannot change the object and often return a mutated new object, leaving the original object unchanged.
This compliant solution correctly updates the
original with the return value from the
Ignoring method return values can lead to unexpected program behavior.
Call Might Return Null (Java)
|Ensure method and constructor return values are used|
Avoid "try", "catch" and "finally" blocks with empty bodies
Passing Parameters and Return Values [CSJ]
CWE-252, Unchecked Return Value