没有相应的 getter 的 Setter
可能的重复:
只写属性有实际应用吗?
没有 setter 的 getter当然,这是完全有道理的。只读属性。明白了,没问题。
但我现在正在维护一些代码,其中有 setter,但没有 getter,我对此感到有点困惑。
我是否有理由对添加吸气剂犹豫不决?我很难想象这样的设置:可以将值更改为调用者想要的任何值(设置器中没有健全性检查),但不能告诉调用者当前值是什么。
代码恰好是 PHP,如果出于某种原因这很重要的话。
Possible Duplicate:
Do write-only properties have practical applications?
A getter without a setter makes total sense, of course. Read-only property. Got it, no problem.
But I'm maintaining some code right now where there are setters but no getters and I'm kind of puzzled by that.
Is there any reason I should be hesitant about adding getters? It's hard for me to imagine a setting where it's OK to change a value to whatever the caller wants (there's no sanity checks in the setters), but wherein it's not OK to tell the caller what the current value is.
The code happens to be PHP, if that matters for some reason.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有很多有效的案例。
考虑一下这个(请原谅我的 PHP - 它是垃圾):
我们不希望密码经过哈希处理或以其他方式在对象外部可见,但我们也不希望将未经过哈希处理的值存储在对象中。我们也不希望破坏密码验证的封装。
There are plenty of valid cases.
Consider this (excuse my PHP - it's rubbish):
We do not ever want the password hashed or otherwise to be visible outside of the object, yet we do not want to store the unhashed value in the object. We also do not want to break encapsulation for password validation.
有一种思想认为,任何不需要满足要求的东西都不应该编码。我想有些人甚至会将这种哲学延伸到 getter 和 setter。
There is a school of thought that anything which is not needed to satisfy the requirements should not be coded. I suppose some people would even extend that philosophy to getters and setters.
正如只写属性有实际应用中指出的吗?< /a>,为随机数生成器设置种子是一个非常简单的情况,其中使用 setter 而不使用 getter 是完全有意义的。
As pointed out in Do write-only properties have practical applications?, setting a seed for a random number generator is a pretty straightforward case where it totally makes sense to have a setter without a getter.