為什么不建議你用去 “! = null” 做判空?
問題
...if (someobject != null) {
someobject.doCalc();}...最終,項目中會存在大量判空代碼,丑陋繁雜。。。如何避免這種情況?是否濫用了判空?
很多業(yè)務(wù)場景需要我們某一特定的時刻去做某件任務(wù),定時任務(wù)解決的就是這種業(yè)務(wù)場景。一般來說,系統(tǒng)可以使用消息傳遞代替部分定時任務(wù),兩者有很多相似之處,可以相互替換場景。
public interface Action {
void doSomething();}
public interface Parser {
Action findAction(String userInput);}其中,Parse有一個接口FindAction,這個接口會依據(jù)用戶的輸入,找到并執(zhí)行對應(yīng)的動作。假如用戶輸入不對,可能就找不到對應(yīng)的動作(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")加小編微信,回復 40 白嫖40套 java/spring/kafka/redis/netty 教程/代碼/視頻 等
掃二維碼,加我微信,回復:40
注意,不要亂回復 沒錯,不是機器人 記得一定要等待,等待才有好東西
評論
圖片
表情
