对象初始化问题的神奇 GET 和 SET

发布于 2024-10-18 05:01:56 字数 406 浏览 3 评论 0原文

我想知道面向类的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

能怎样 2024-10-25 05:01:56

这里真正的问题是使用 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.

海夕 2024-10-25 05:01:56

我认为这个解决方案很好。使用设置器的原因之一是确保您的底层字段永远不会保存错误的值。

I think this solution is fine. One reason to have setters is to make sure your under laying fields never hold incorrect values.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文