Nested Objects Best Practice

2019-03-28 13:12发布

What is the best practice for referencing nested objects?

Say I have the following:

class Outer {
 private InnerA innerA;
 //getters and setters
}

class InnerA {
  private InnerB innerB;
  //getters and setters
}

class InnerB {
  private String someString;
  //getters and setters
}

and in my controller or service class I need to check the someString String variable of the InnerB class to make sure it is not null or not empty so I do this:

if (getOuter().getInnerA().getInnerB().getSomeString() != null && !getOuter().getInnerA().getInnerB().getSomeString().equalsIgnoreCase("") {
  //do something
}

To me this looks messy and could have issues if the nested objects themselves are null.

Do I create getters ans setters in the parent objects for the child objects checking for null? Just wondering what the best practice was if any and/or what some of you do in your code?

9条回答
走好不送
2楼-- · 2019-03-28 13:43

If any of those objects can be null, then you have to check for null before calling a getter on this object, of course.

But this kind of chaining is a bad smell of a lack of encapsulation (anemic objects having just data, and no behavior). You're violating the law of Demeter : don't talk to strangers.

查看更多
Evening l夕情丶
3楼-- · 2019-03-28 13:47

You can use Apache Commons BeanUtils to navigate through your nested properties like this:

Add method getSomeString() to your Outer class and write something like

PropertyUtils.getNestedProperty(this, "innerA.innerB.someString");

I can't remember if that PropertyUtils class check null properties, but I would look Apache Commons BeanUtils site.

Hope this helps!

查看更多
仙女界的扛把子
4楼-- · 2019-03-28 13:49

You have two options:

  1. Use Null Object design pattern
  2. Wait for Java 7 Java 8 null safe operator.
查看更多
登录 后发表回答