当业务规则具有属性可访问性时,如何测试它?
这是问题所在。我有一个业务对象,它有一个名为 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您可以只在构造函数中设置它,则可以将该字段设置为只读。
If you can afford to only set it only in constructor you can make the field read only.