对象初始化问题的神奇 GET 和 SET
我想知道面向类的 DDD 的最佳实践。
由于我正在名为 ChangeX(string x) 的自定义设置器中进行域验证,因此我可能会被迫使用它作为属性。
公共虚拟字符串示例 { get; 私人套装; }
,这不是很好,因为它使我无法使用对象初始化功能,例如:
新对象 { 示例 = "一些示例" }
我想为什么不将自定义集传递到属性集中呢?像这样
公共虚拟字符串示例 { get { 返回示例; } 放 { 更改示例(值); } }
这会导致任何问题吗 它违反最佳实践吗?
谢谢。
I would like to know the best practice for a class oriented DDD.
Since i am doing domain validation in custom setters named ChangeX(string x) i might be pushed to use this as property.
public virtual string example { get;
private set; }
However, that not very good since it disable me from using the object initialization feature such as :
new Object { Example = "Some example"
}
So i though why not passing the custom set into the property set ? like this
public virtual string Example { get {
return Example; } set {
ChangeExample(value); } }
Is this can lead to any problems ? it is against best practices ?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这里真正的问题是使用 setter 本身。你为什么需要它们?
当你使用setter时,你就失去了隔离性——你可以从外部修改对象的状态,而他们不知道这一点。这导致了程序代码。
相反,您应该要求对象做一些最终可能导致它们改变自己状态的事情(而不仅仅是修改它们的状态)。
Real problem here is using setters as such. Why do You need them?
When You use setters, You lose isolation - You can modify state of objects from outside w/o them knowing that. That leads to procedural code.
In contrast - You should ask objects to do something (not just modify their state) that would eventually might lead to them changing their own state.
我认为这个解决方案很好。使用设置器的原因之一是确保您的底层字段永远不会保存错误的值。
I think this solution is fine. One reason to have setters is to make sure your under laying fields never hold incorrect values.