Mots clés : javanullpointerexceptionjava
92
assert <condition>
assert <condition> : <object>
public interface Action { void doSomething(); } public interface Parser { Action findAction(String userInput); }
public class MyParser implements Parser { private static Action DO_NOTHING = new Action() { public void doSomething() { /* do nothing */ } }; public Action findAction(String userInput) { // ... if ( /* we can't find any actions */ ) { return DO_NOTHING; } } }
Parser parser = ParserFactory.getParser(); if (parser == null) { // now what? // this would be an example of where null isn't (or shouldn't be) a valid response } Action action = parser.findAction(someInput); if (action == null) { // do nothing } else { action.doSomething(); }
ParserFactory.getParser().findAction(someInput).doSomething();
try { ParserFactory.getParser().findAction(someInput).doSomething(); } catch(ActionNotFoundException anfe) { userConsole.err(anfe.getMessage()); }
public Action findAction(final String userInput) { /* Code to return requested Action if found */ return new Action() { public void doSomething() { userConsole.err("Action not found: " + userInput); } } }
89
@NotNull public static String helloWorld() { return "Hello World"; }
@Nullable public static String helloWorld() { return "Hello World"; }
public static void main(String[] args) { String result = helloWorld(); if(result != null) { System.out.println(result); } }
void someMethod(@NotNull someParameter) { }
someMethod(null);
@Nullable iWantToDestroyEverything() { return null; }
iWantToDestroyEverything().something();
75
public void method(Object object) { if (object == null) { throw new IllegalArgumentException("..."); }
public String getFirst3Chars(String text) { return text.subString(0, 3); }
if (object == null) { // something } else { // something else }
68
public String getPostcode(Person person) { return person?.getAddress()?.getPostcode(); }