为什么不建议你用去 “! = 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 让“干坡坡”变“金窝窝” 7904795
- 2 多地已明确:招聘破除35岁年龄限制 7809495
- 3 少爷现在所有人都知道你考完了 7712096
- 4 让正能量成为网络空间主旋律 7616216
- 5 老师参加高考:不过640分请学生吃饭 7524124
- 6 谢霆锋替身车手去世 年仅37岁 7424439
- 7 爸妈送烧烤花 高考女儿边哭边闻味 7330154
- 8 日本火箭发射5秒后爆炸 7232245
- 9 刘亦菲李沁中间这位女士 7137412
- 10 带你看懂5月CPI和PPI数据 7044948