為什么我不建議你用 “obj ! = null " 做判空?

轉自:CSDN 作者:lizeyang
blog.csdn.net/lizeyang/article/details/40040817
...if (someobject != null) {
someobject.doCalc();}...最終,項目中會存在大量判空代碼,多么丑陋繁冗!如何避免這種情況?我們是否濫用了判空呢?
public interface Action {
void doSomething();}
public interface Parser {
Action findAction(String userInput);}其中,Parse有一個接口FindAction,這個接口會依據(jù)用戶的輸入,找到并執(zhí)行對應的動作。假如用戶輸入不對,可能就找不到對應的動作(Action),因此findAction就會返回null,接下來action調(diào)用doSomething方法時,就會出現(xiàn)空指針。
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();}2、精簡
ParserFactory.getParser().findAction(someInput).doSomething();其他回答精選:
1、如果要用equal方法,請用object<不可能為空>.equal(object<可能為空>))
例如使用 :
"bar".equals(foo)而不是
foo.equals("bar")評論
圖片
表情
