嵌套对象最佳实践 [英] Nested Objects Best Practice

查看:62
本文介绍了嵌套对象最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

引用嵌套对象的最佳实践是什么?

What is the best practice for referencing nested objects?

说我有以下内容:

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

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

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

在我的控制器或服务类中,我需要检查InnerB类的someString String变量以确保其不为null或不为空,所以我可以这样做:

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
}

在我看来,这看起来很杂乱,如果嵌套对象本身为null,则可能会出现问题.

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

我是否在父对象中为检查null的子对象创建getters和setters?只是想知道最佳实践是什么,和/或你们中的某些人在代码中做了什么?

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?

推荐答案

如果这些对象中的任何一个可以为null,那么您当然必须在对该对象调用getter之前检查null.

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.

这篇关于嵌套对象最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆