為什么不建議你用去 “! = null” 做判空?
往期熱門文章:
1、SpringBoot 配置文件敏感信息如何加密? 2、線上訂單號重復(fù)了?一招搞定它! 3、一款高顏值的MySQL管理工具:Sequel Pro 4、2021 年 GitHub 最佳開源軟件榜單
為了避免空指針調(diào)用,我們經(jīng)常會看到這樣的語句
...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")轉(zhuǎn)自:stackoverflow
最近熱文閱讀:
1、SpringBoot 配置文件敏感信息如何加密? 2、線上訂單號重復(fù)了?一招搞定它! 3、一款高顏值的MySQL管理工具:Sequel Pro 4、2021 年 GitHub 最佳開源軟件榜單 5、Logback這樣配置,性能提升10倍! 6、揭曉 2021 編程語言排行榜 7、還在用策略模式解決 if-else?Map+函數(shù)式接口方法才是YYDS! 8、牛客網(wǎng):為什么不能將實數(shù)作為 HashMap 的 key? 9、RedisJson發(fā)布官方性能報告,性能碾壓ES和Mongo 10、分布式數(shù)據(jù)一致性思考-B端系統(tǒng)一致性 關(guān)注公眾號,你想要的Java都在這里
評論
圖片
表情
