是“getSomething()”吗?一个糟糕的方法命名模式?
方法应该告诉对象要做什么,例如:
circle.paint()
但是如果我告诉对象 getSomething()
,我会告诉对象 get “something”(从任何地方)并且不返回“某物”,get
方法的典型用法是什么(getName()
将返回“姓名”)。
我认为将该方法命名为 returnSomething()
更为正确。
那么 get
(通常使用的)是一个糟糕的命名模式吗?
Methods should tell objects what to do, for example:
circle.paint()
But if I tell an object to getSomething()
, I would tell the object to get "something" (from anywhere) and not to return "something", what is the typical usage of get
methods (getName()
would return "name").
I think that it would be more correct to name the method returnSomething()
.
So is get
(as used typically) a bad naming pattern?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
约定可能会根据您使用的语言而有所不同,在 php(不支持 getter/setter 方法)中,以下内容很常见:
$myObject=>setSomething($value)
- set表示“某物”的 $myObject 的内部变量到 $value$myObject=>getSomething()
- 返回表示“某物”的 $myObject 的内部变量这在 C# 等语言中不太常见,因为支持 getter/setter 方法,您可能会执行以下操作:
然后您可以使用点语法来访问私有变量:
The convention probably varies depending on the language you are using, in php (which doesn't support getter/setter methods) the following is quite common:
$myObject=>setSomething($value)
- sets an internal variable of $myObject representing 'something' to $value$myObject=>getSomething()
- returns an internal variable of $myObject representing 'something'This is less common in languages like C#, which support getter/setter methods, where you'd probably do the following:
Then you can use dot syntax to access the private variable:
我个人不使用
Get
前缀。我在检索某些内容的方法中使用的唯一前缀是“指标”的
Is
。例如 payment.IsOverdue()
至于 setter 方法 - 那些不应该存在。
对象状态应该通过调用的行为由其自身定义。
Get
不是必需的,因为当我们请求某些东西时,应该使用名词来命名。I personally don't use
Get
prefix.Only prefix I do use for methods that retrieves something is
Is
for "indicators".E.g. payment.IsOverdue()
As for setter methods - those shouldn't exist.
Object state should be defined by itself through invoked behavior.
Get
is not necessary because when we are asking for something, nouns should be used for naming.Deamon,首先我认为这件事有点取决于语言。其次,我有这个 方法命名指南。
我还可以说,在我工作的公司中,我们总是使用
GetSomething()
、GetYourAcceptRateHigher()
等名称作为我们的方法。Deamon, first of all I think this thing kinda depends on the language.Secondly, I've got this Method Naming Guidelines for you.
I can also say that in the company I am working we always use names like
GetSomething()
,GetYourAcceptRateHigher()
for our methods.