为什么不建议你用去 “! = null” 做判空?
↓推荐关注↓
为了避免空指针调用,我们经常会看到这样的语句
...if (someobject != null) {
someobject.doCalc();}...
最终,项目中会存在大量判空代码,丑陋繁杂。。。如何避免这种情况?是否滥用了判空?
很多业务场景需要我们某一特定的时刻去做某件任务,定时任务解决的就是这种业务场景。一般来说,系统可以使用消息传递代替部分定时任务,两者有很多相似之处,可以相互替换场景。
public interface Action {
void doSomething();}
public interface Parser {
Action findAction(String userInput);}
其中,Parse有一个接口FindAction,这个接口会依据用户的输入,找到并执行对应的动作。假如用户输入不对,可能就找不到对应的动作(Action),因此findAction就会返回null,接下来action调用doSomething方法时,就会出现空指针。
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")
转自:stackoverflow
- EOF -
关注「程序员的那些事」加星标,不错过圈内事
点赞和在看就是最大的支持❤️
关注公众号:拾黑(shiheibook)了解更多
[广告]赞助链接:
四季很好,只要有你,文娱排行榜:https://www.yaopaiming.com/
让资讯触达的更精准有趣:https://www.0xu.cn/

随时掌握互联网精彩
赞助链接
排名
热点
搜索指数
- 1 旧物换新 万亿市场添“活力” 7904738
- 2 印度警方称坠机事故有1名幸存者 7809099
- 3 幸存者跳机逃生 自行从残骸中走出 7714407
- 4 中国外贸在复杂环境中稳健前行 7617479
- 5 印度坠机事故致超290人死亡 7520859
- 6 B站崩了 7426228
- 7 网警提醒:高考后考生家长仍需警惕 7332694
- 8 坠毁客机乘客登机前发视频:再见印度 7232446
- 9 42岁百万网红“草帽姐”确诊肝病 7141773
- 10 众多明星走红毯 王子文不慎摔倒 7040818