独立的获取/设置方法,还是结合使用? [英] Independent getter/setter methods, or combined?

查看:62
本文介绍了独立的获取/设置方法,还是结合使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在从事项目工作时,我一直在进行一些更改,并浏览现有的框架API文档以获取见识.

While working on a project, I've been making some changes and browsing around existing framework API docs for insight.

在仔细阅读Kohana文档时,我注意到任何给定类的getters/setter方法通常都是结合在一起的:

While perusing the Kohana docs, I noticed that the getters/setters of any given class are typically combined:

public function someProperty($value = null){
    if(is_null($value){
        return $this->_someProperty;
    }
    $this->_someProperty = $value;
    return $this;
}

而不是:

public function setSomeProperty($value){
    $this->_someProperty = $value;
    return $this;
}

public function getSomeProperty(){
    return $this->_someProperty;
}

除了减少给定类的方法数量之外,这样做是否有价值(前者)?我一直在理解方法(一般是功能)应该更描述动作.当其他有经验的开发人员看到这一点时,他们会畏缩吗?

Is there any value in doing this (the former), beyond lessening the method count of a given class? I was always under the understanding that methods (functions in general) should be more descriptive of an action. Do other experienced developers cringe, even a tiny bit, when they see this?

我只是惊讶地看到一个流行的框架使用了这样的约定(我当然没有使用Kohana )

I was just surprised to see a popular framework use such conventions (I haven't used Kohana of course)

推荐答案

我认为这是一种不好的做法,因为它违反了 CommandQuerySeparation .设置值将改变状态(命令).获取值是在询问状态(查询).一种方法不能同时做到,而只能做一件事.

I consider this bad practise because it violates CommandQuerySeparation. Setting a value is changing state (Command). Getting a value is asking for state (Query). A method should not do both, but one thing only.

此外,在仅称为用户名的情况下,方法的作用并不十分明显.没有动词,例如get或set.在您的示例中,情况甚至更糟,因为返回值要么是对象本身,要么是属性值,因此其不一致.

Also, it's not really obvious what a method does when it's just called username, e.g. does not have a verb, like get or set. This gets even worse in your example, because the return value is either the object itself or the property value, so its not consistent.

此外,应谨慎使用 getter(和setter),因为它们会快速使您的API复杂化.您拥有的getter和setter越多,该对象的协作者就需要有关该对象的知识越多.如果您发现自己的对象向其他对象询问内部问题,则很可能是您错失了职责.

Moreover, getters (and setters) should be used sparingly as they will quickly convolute your API. The more getters and setters you have, the more knowledge about an object is required by collaborators of that object. If you find your objects asking other objects about their internals, chances are you misplaced the responsibilities.

这篇关于独立的获取/设置方法,还是结合使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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