Sometimes it is usual to define something like a method contract.
I am doing this via Spring Asserts
:
org.springframework.util.Assert;
Assertion utility class that assists in validating arguments. Useful
for identifying programmer errors early and clearly at runtime.
For example, if the contract of a public method states it does not
allow null arguments, Assert can be used to validate that contract.
Doing this clearly indicates a contract violation when it occurs and
protects the class's invariants.
Typically used to validate method arguments rather than configuration
properties, to check for cases that are usually programmer errors
rather than configuration errors. In contrast to config initialization
code, there is usally no point in falling back to defaults in such
methods.
This class is similar to JUnit's assertion library. If an argument
value is deemed invalid, an IllegalArgumentException is thrown
(typically).
In your case:
public void doSomething(String str) {
Assert.notNull(str);
Double val = Double.parseDouble(str); // Nullpointer not possible here if the contract was not injured.
// Other code
}
If a null value is passed by any developer the contract was not fullfilled and a IlligalArgumentException
is thrown.
Easy testable via Junit:
/**
* Check case that passed string is null.
*/
@Test(expected = IllegalArgumentException.class)
public void testDoSomething_StringIsNull() {
mClassUnderTest.doSomething(null);
}