為什么不建議你用去 “! = null” 做判空?
往期熱門文章:
1、SpringBoot 配置文件敏感信息如何加密? 2、線上訂單號(hào)重復(fù)了?一招搞定它! 3、一款高顏值的MySQL管理工具:Sequel Pro 4、2021 年 GitHub 最佳開源軟件榜單
為了避免空指針調(diào)用,我們經(jīng)常會(huì)看到這樣的語句
...if (someobject != null) {
someobject.doCalc();}...最終,項(xiàng)目中會(huì)存在大量判空代碼,丑陋繁雜。。。如何避免這種情況?是否濫用了判空?
很多業(yè)務(wù)場(chǎng)景需要我們某一特定的時(shí)刻去做某件任務(wù),定時(shí)任務(wù)解決的就是這種業(yè)務(wù)場(chǎng)景。一般來說,系統(tǒng)可以使用消息傳遞代替部分定時(shí)任務(wù),兩者有很多相似之處,可以相互替換場(chǎng)景。
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,接下來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")轉(zhuǎn)自:stackoverflow
最近熱文閱讀:
1、SpringBoot 配置文件敏感信息如何加密? 2、線上訂單號(hào)重復(fù)了?一招搞定它! 3、一款高顏值的MySQL管理工具:Sequel Pro 4、2021 年 GitHub 最佳開源軟件榜單 5、Logback這樣配置,性能提升10倍! 6、揭曉 2021 編程語言排行榜 7、還在用策略模式解決 if-else?Map+函數(shù)式接口方法才是YYDS! 8、牛客網(wǎng):為什么不能將實(shí)數(shù)作為 HashMap 的 key? 9、RedisJson發(fā)布官方性能報(bào)告,性能碾壓ES和Mongo 10、分布式數(shù)據(jù)一致性思考-B端系統(tǒng)一致性 關(guān)注公眾號(hào),你想要的Java都在這里
評(píng)論
圖片
表情
