问题描述
假设我想执行以下命令:
Let's say I'd like to perform the following command:
house.getFloor(0).getWall(WEST).getDoor().getDoorknob();
为了避免 NullPointerException,如果出现以下情况,我必须执行以下操作:
To avoid a NullPointerException, I'd have to do the following if:
if (house != null && house.getFloor(0) && house.getFloor(0).getWall(WEST) != null
&& house.getFloor(0).getWall(WEST).getDoor() != null) ...
有没有一种方法或者一个已经存在的 Utils 类可以更优雅地做到这一点,让我们说一下类似下面的内容?
Is there a way or an already existing Utils class that does this more elegantly, let's say something like the following?
checkForNull(house.getFloor(0).getWall(WEST).getDoor().getDoorknob());
推荐答案
最好的方法是避免链条.如果您不熟悉迪米特法则 (LoD),我认为您应该这样做.您已经给出了一个完美的消息链示例,该消息链与它不了解的类过于密切.
The best way would be to avoid the chain. If you aren't familiar with the Law of Demeter (LoD), in my opinion you should. You've given a perfect example of a message chain that is overly intimate with classes that it has no business knowing anything about.
德米特法则:http://en.wikipedia.org/wiki/Law_of_Demeter
这篇关于检查“get"链要求为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!