来自:李良逸
链接: http:// blog.imuxuan.com/archiv es/86
判空灾难
![3eb2e7772ae94c35866ab049ce286b91.png](https://i-blog.csdnimg.cn/blog_migrate/8859ed4f15bc965f3a406f7cfa60083d.jpeg)
作为搬砖党的一族们,我们对判空一定再熟悉不过了,不要跟我说你很少进行判空,除非你喜欢 NullPointerException。
不过 NullPointerException对于很多猿们来说,也是 Exception家族中最亲近的一员了。
![711a9a47edbd4bcb988afbd921011715.png](https://i-blog.csdnimg.cn/blog_migrate/431c505dcf0ca058e653c80042bf312f.png)
为了避免 NullPointerException来找我们,我们经常会进行如下操作:
if (data != null) {
do sth.
}如果一个类中多次使用某个对象,那你可能要一顿操作,so:
如果一个类中多次使用某个对象,那你可能要一顿操作,so:
![b02845f7114a29870b552cc930a20ed7.png](https://i-blog.csdnimg.cn/blog_migrate/2144fb4be6f620f14a28aa58d6454c66.jpeg)
世界第九大奇迹”就这样诞生了。Maybe你会想,项目中肯定不止你一个人会这样一顿操作,然后按下 Command+Shift+F,真相就在眼前:
![cfb599ba3565960e72175552e9e72352.png](https://i-blog.csdnimg.cn/blog_migrate/11a266f9a320b26a9e2ddf3b21d14b70.png)
What,我们有接近一万行的代码都是在判空?
好了,接下来,要进入正题了。
NullObject模式
对于项目中无数次的判空,对代码质量整洁度产生了十分之恶劣的影响,对于这种现象,我们称之为“判空灾难”。
那么,这种现象如何治理呢,你可能听说过 NullObject模式,不过这不是我们今天的武器,但是还是需要介绍一下 NullObject模式。
什么是NullObject模式呢?
In object-oriented computer programming, a null object is an object with no referenced value or with defined neutral ("null") behavior. The nu