将 getter 和 setter 组合成 gettersetter
就“好代码”而言,将 set 和 get 方法合而为一是否可以接受?像这样:
public function dir($dir=null) {
if (is_null($dir)) return $this->dir;
$this->dir = $dir;
}
In terms of "good code", is it acceptable to combine set and get methods into one? Like this:
public function dir($dir=null) {
if (is_null($dir)) return $this->dir;
$this->dir = $dir;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是相当可怕的。一方面,它使得无法将该值设置为 null。
在区分 undefined 和 null 的语言中,使用未定义的值而不是 null 来执行此操作是合理的。
返回或未返回的内容之间的不匹配在许多语言中甚至是无效的。无论哪种情况,为什么不返回它,以允许 x.dir = y.dir = someValue 的合理链接?但这是一个小问题,我的第一段是我的主要答案。
It's pretty dreadful. It makes it impossible to set the value to null, for one thing.
In a language that distinguished undefined from null, then it would be reasonable to do this with that undefined value, rather than null.
The mismatch between something being returned or not isn't even valid in many languages. In either case, why not return it anyway, to allow reasonable chaining of
x.dir = y.dir = someValue
? But that's a nick-pick, my first paragraph is my main answer.我最初的想法是,代码更难阅读,因此更难维护。我已经达到了使用 C# 的 auto 属性或仅使用公共字段的程度。
My initial thought is no the code is harder to read and therefore maintain. I have gotten to where I either use C#'s auto property or just a public field.
这种模式至少在 jQuery 中很常见;我想说这很好。
This pattern is at least very common in jQuery; I'd say it is fine.