确定在Java中用于方法名称的动词 [英] determining which verb to use for method names in Java
问题描述
我知道命名约定之所以重要,有很多原因,其中大部分与使您的代码更具可读性,更易于集成到更大的项目等有关.在Java中,大多数约定都要求方法名称在lowerCamelCase
中以动词开头.
I understand that naming conventions are important for a number of reasons, most having to do with making your code more readable and easier to integrate into larger projects, etc. In Java, most conventions require that method names be in lowerCamelCase
begin with a verb.
我的问题是:如何选择动词来开始方法名称?
My question is: how do I choose the verb to begin the method name?
为了使这个问题不再那么模糊,我经常遇到这样的情况:我对方法名称的首选是描述输出的名词.在这些情况下,我通常会在名词字体中添加通用动词(例如get
,generate
,calculate
等)之间感到不舒服,以符合动词规则.是否有关于何时使用哪种通用指南?
To make this question less vague, I'm often in the situation where my first choice for a method name is a noun describing the output. In these cases, I'm usually torn between appending generic verbs such as get
, generate
, calculate
, etc in font of the noun to conform to the verb rule. Are there general guidelines for when to use which?
这是一个例子.我有一个方法,该方法采用double[] array
和int k
并返回double[] newArray
,这是array
的长度k
移动平均值,即newArray[i] = (array[i-k+1]+...+array[i])/k
,并且有些修饰使newArray
的长度与array
.我的倾向是将此方法称为movingAverage
,因为它是返回的内容,但由于它不是以动词开头的,因此就可以了.我应该将此方法称为getMovingAverage
或generateMovingAverage
或calculateMovingAverage
还是真的无关紧要?
Here's an example. I have a method that takes double[] array
and an int k
and returns double[] newArray
which is the length k
moving average of array
, i.e. newArray[i] = (array[i-k+1]+...+array[i])/k
with some fudging to make newArray
the same length as array
. My inclination is to call this method movingAverage
since that's what it returns, but that's out since it doesn't begin with a verb. Should I call this method getMovingAverage
or generateMovingAverage
or calculateMovingAverage
or does it not really matter?
推荐答案
我通常问自己:
此方法在做什么?
答案决定了应调用什么方法.当然,它完全独立于程序员.
The answer dictates what the method should be called. It is completely independent of the programmer, of course.
注意::如果您不能简洁描述方法的作用,则可能是方法做得太多,应该分开.
Note: If you can't succinctly describe what the method is doing, it's probably doing too much and should be split up.
选择方法的动词:
- 执行计算:计算
- 获取数据:获取或获取
- 更改数据:设置或更改
- 删除数据:删除或删除
- 转换:转换
- 启动操作:开始或启动
- 停止操作:停止或取消
- Performing calculation(s): calculate
- Retrieving data: get or retrieve
- Mutating data: set or change
- Deleting data: delete or remove
- Converting: convert
- Initiating an action: start or initiate
- Stopping an action: stop or cancel
现在,并非所有方法都以动词开头;但他们确实不需要.如果您阅读:
Now, not all methods begin with a verb; but they really don't need to. If you read:
... myString.length();
或
... myArray.size();
您确切地知道发生了什么-不需要动词.对于Java层次结构中更高级别的许多类方法而言,这都是正确的.集合,数学等.只要名称准确传达方法的作用,就可以了.
you know exactly what is going on - no verb required. This is true for many class methods higher up in the Java hierarchy; Collections, Math, etc. As long as the name accurately communicates what the method does, it's fine.
这篇关于确定在Java中用于方法名称的动词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!