当业务规则具有属性可访问性时,如何测试它?

发布于 2024-10-16 07:23:49 字数 411 浏览 8 评论 0原文

这是问题所在。我有一个业务对象,它有一个名为 RegisterDate 的字段。商业规则一如往常,一旦设定就无法更改。

我首先考虑将此字段实现为属性并将 setter 定义为受保护,以防止用户在创建对象后使用(和设置)它。但经过思考一段时间后,我在属性可访问性规则中偷偷添加了一条业务规则。

我的第二个想法是让属性设置器公开,在设置它时实现异常,这使得业务规则非常明确。将会有一个测试用例,期望每次有人尝试设置该属性时该属性都会抛出异常。

好吧,但是为了避免某种行为,有很多样板代码,为什么不保护这些东西,甚至避免代码其他部分的误用呢?但后来我想知道,如果另一个开发人员不小心更改了属性可访问性并再次将其公开,并且业务对象的用户开始使用该字段违反业务规则怎么办?

对于这种情况,最好的方法是什么?你会如何解决这个问题?

Here is the catch. I have a business object that has a field named RegisterDate. The business rule as usual says that once it is set, can't be changed.

My first thinking about implementing this field as a property and defining the setter as protected, preventing users from using (and setting) it after the object is created. But after thinking a while I got me sneaking a business rule in a property accessibility rule.

My second thought was to leave the property setter public, implement an exception when setting it, which makes the business rule pretty explicit. There will be a test case that expect the property to throw an exception every time someone tries to set it.

Well, but that's a lot of boilerplate to avoid a behavior, why not making the thing protected after all, avoiding even misuse in other parts of the code? But then I wondered, what if another developer accidentally changes the property accessibility and makes it public again and the users of the business object starts using this field violating the business rule?

What is the best approach for this situation? How would you solve this issue?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

铁轨上的流浪者 2024-10-23 07:23:49

如果您可以只在构造函数中设置它,则可以将该字段设置为只读。

public class SomeClass
{
  public SomeClass(DateTime regDate)
  {
     registerDate = regDate;
  }

  public DateTime RegisterDate { get { return registerDate; } }

  private readonly DateTime registerDate;
}

If you can afford to only set it only in constructor you can make the field read only.

public class SomeClass
{
  public SomeClass(DateTime regDate)
  {
     registerDate = regDate;
  }

  public DateTime RegisterDate { get { return registerDate; } }

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