C#/面向对象设计-保持有效的对象状态 [英] C# / Object oriented design - maintaining valid object state

查看:141
本文介绍了C#/面向对象设计-保持有效的对象状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在设计类时,应将保持有效状态的逻辑合并到类中还是在其外部?也就是说,属性应该在无效状态(例如,值超出范围等)上引发异常,还是应该在构造/修改类的实例时执行此验证?

When designing a class, should logic to maintain valid state be incorporated in the class or outside of it ? That is, should properties throw exceptions on invalid states (i.e. value out of range, etc.), or should this validation be performed when the instance of the class is being constructed/modified ?

推荐答案

它属于该类.除了类本身(及其委托的任何帮助者)之外,什么都不应该知道或关心确定有效或无效状态的规则.

It belongs in the class. Nothing but the class itself (and any helpers it delegates to) should know, or be concerned with, the rules that determine valid or invalid state.

这篇关于C#/面向对象设计-保持有效的对象状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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