检查“获取”链调用null [英] Check chains of "get" calls for null
问题描述
假设我想执行以下命令:
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
这篇关于检查“获取”链调用null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!