使用“单一责任原则”迫使我的集装箱有公共设施 [英] Using the "Single Responsibility Principle" forces my containers to have public setters

查看:100
本文介绍了使用“单一责任原则”迫使我的集装箱有公共设施的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力设计遵循SOLID原则。我发现当您使用单一责任原则(SOLID的S)时,通常必须在数据容器和数据处理器之间拆分类。例如,如果我有一个具有从DB读取的5个属性的类人员,而不是将所有内容放在一个类中,我将创建一个具有属性的Person类和另一个从数据库读取该信息并创建Person的PersonReader类。



如果我这样做,我必须打开Person属性,所以PersonReader可以访问它们,但是我把所有内容都放在黑盒子中,并且使属性只能读取。 p>

我错过了什么,这是否是这个原则的缺点?



提前感谢



编辑:我已经将个人作家改为一个读者,因为开始时没有必要将属性设置器公开。

解决方案

也许我错过了一些东西,但是为什么不写一个接受所有属性的Person类的构造函数?
这样一来,PersonReader就可以创建一个人,而无需打开该人的属性。



另一个选项是将该人员的属性设置为内部(并且如果它在不同的程序集中),则可以让组装内容对于PersonReader的程序集可见。这将允许您访问该人员的属性,但将阻止任何人将其更改为装配体外。


I'm trying hard to design following the SOLID principles. What I've found is that when you use the "Single Responsibility Principle" (the S of SOLID) you usually have to split classes between the data containers and the data processors. For example If I have a class person with 5 properties that is read from DB instead of putting everything inside a class I create a Person class with the properties and another PersonReader class that reads that information from the database and creates the Person.

If I do that I have to open the Person properties so PersonReader could access them but then I have less encapsulation than putting everything inside a black box and making the properties only readable.

Am I missing something or is this a drawback of this principle?

Thanks in advance

EDIT: I've changed the person writer to a person reader because there was no need to make property setters public at the beginning.

解决方案

Maybe I'm missing something, but why won't you write a constructor for Person class which accepts all it's properties? This way the PersonReader will be able to create a person without you opening the person's properties.

Another option is to mark the setter of the person's properties as internal (And make the assembly internals visible to the assembly of the PersonReader, if it's in a different assembly). This will allow you to access the person properties, but will prevent anyone to change them outside of the assembly.

这篇关于使用“单一责任原则”迫使我的集装箱有公共设施的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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