OOD - 设置一次值,使其无法更改
我正在尝试了解信息隐藏的原理。假设我有一个车辆类,其中包含 getSpeed、setSpeed、getEngine、setEngine、getVIN、setVIN 等方法。为了强制执行信息隐藏,我不想为客户端类提供 setVIN 的能力,因为车辆只有一个 VIN (我可能是错的)。我对如何使此类应用信息隐藏感到有点困惑。我不想将 setVIN 设为私有。但是如何设置VIN一次并且之后不允许再次设置呢?或者我应该这样做吗?
I am trying to understand the principle of information hiding. Suppose that I have a vehicle class with methods such as getSpeed, setSpeed, getEngine, setEngine, getVIN, setVIN, etc. To enforce info hiding, I wouldn't want to give client classes the ability to setVIN since a vehicle only has one VIN (I might be wrong). I am kind of confused on how to make this class apply info hiding. I wouldn't want to make setVIN to private. But how do you set the VIN once and not allow it to be set again afterwards? Or should I even do it that way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
信息隐藏意味着您不会暴露内部 VIN 字段以供外部直接修改。拥有 setter 并不违反隐藏原则,因为您可以控制字段的修改。
在您的情况下,如果您想确保 VIN 仅设置一次,最好的方法是在构造函数中设置它,然后删除 setVIN。
顺便说一句,虽然这是一个一般性问题(这很好),但如果您心中有一种特定的语言,那么它可能值得一提。例如,某些语言不允许非默认构造函数。在这种语言中,我会保留 setVIN,但让它在调用时检查 VIN 是否已设置。如果有,则忽略该调用,或引发异常。
Information hiding means you're not exposing the internal VIN field for direct modification from the outside. Having a setter does not violate the hiding principle, because you have the control over the fields modification.
In your case, if you want to make sure the VIN is only set once, best way to do it is by setting it in the constructor, and removing the setVIN.
BTW, although this is a general question (which is fine), if you have a specific language in mind, it might be worth mentioning. Some languages do not allow non-default constructors, for instance. In that kind of language, I'd leave the setVIN, but have it check whether the VIN has already been set when called. If it had, either ignore the call, or throw an exception.
从概念上讲,仅仅因为类/对象具有属性,并不意味着它应该是公共的。 “属性”可以被分配和分配。用“getter”和“改变” “setter”函数,但您只能公开您需要的函数。
你可能会说,“给我看代码”:
它没有经过测试,但是,我认为,它解释了我的观点。
Just because a class / object has a property, conceptually speaking, it doesn't mean it should be public. A "property" can be assigned & changed with "getter" & "setter" functions, but you may only expose as public the ones you need.
You may say, "Show me the code":
Its not tested, but, I think, it explains my point.