没有相应的 getter 的 Setter

发布于 2024-12-14 00:38:23 字数 413 浏览 1 评论 0 原文

可能的重复:
只写属性有实际应用吗?

没有 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 技术交流群。

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

发布评论

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

评论(3

醉生梦死 2024-12-21 00:38:24

有很多有效的案例。

考虑一下这个(请原谅我的 PHP - 它是垃圾):

class User {
    protected $password;
    public function setPassword($newPassword) {
        $this->password = sha1($newPassword);
    }
    public function verifyPassword($against) {
        return $this->password == sha1(against);
    }
}

我们不希望密码经过哈希处理或以其他方式在对象外部可见,但我们也不希望将未经过哈希处理的值存储在对象中。我们也不希望破坏密码验证的封装。

There are plenty of valid cases.

Consider this (excuse my PHP - it's rubbish):

class User {
    protected $password;
    public function setPassword($newPassword) {
        $this->password = sha1($newPassword);
    }
    public function verifyPassword($against) {
        return $this->password == sha1(against);
    }
}

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.

旧伤还要旧人安 2024-12-21 00:38:24

有一种思想认为,任何不需要满足要求的东西都不应该编码。我想有些人甚至会将这种哲学延伸到 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.

紅太極 2024-12-21 00:38:24

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.

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