別再用 “! = null” 做判空了!
...if (someobject != null) {
someobject.doCalc();}...最終,項(xiàng)目中會(huì)存在大量判空代碼,丑陋繁雜。。。如何避免這種情況?是否濫用了判空?
public interface Action {
void doSomething();}
public interface Parser {
Action findAction(String userInput);}其中,Parse有一個(gè)接口FindAction,這個(gè)接口會(huì)依據(jù)用戶的輸入,找到并執(zhí)行對(duì)應(yīng)的動(dòng)作。假如用戶輸入不對(duì),可能就找不到對(duì)應(yīng)的動(dòng)作(Action),因此findAction就會(huì)返回null,接下來(lái)action調(diào)用doSomething方法時(shí),就會(huì)出現(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、精簡(jiǎn)
ParserFactory.getParser().findAction(someInput).doSomething();其他回答精選:
1、如果要用equal方法,請(qǐng)用object<不可能為空>.equal(object<可能為空>))
例如使用:
"bar".equals(foo)而不是? ?
foo.equals("bar")??如果喜歡本篇,歡迎「點(diǎn)贊、在看?」,下次見(jiàn)
評(píng)論
圖片
表情
