在Java中确定方法名使用哪个动词

32

我知道命名规范在许多方面都很重要,大多数涉及使您的代码更易读和更容易集成到更大的项目中等。在Java中,大多数惯例要求方法名称采用lowerCamelCase格式并以动词开头。

我的问题是:如何选择作为方法名称开头的动词?

为了让这个问题更具体,我经常遇到的情况是,我首选的方法名称是描述输出的名词。在这些情况下,我通常会犹豫不决,应该在名词前加上通用动词,例如getgeneratecalculate等,以符合动词规则。是否有一般性的准则来确定何时使用哪种动词?

以下是一个例子。我有一个方法,它接受double[] array和一个int k,并返回double[] newArray,它是array的长度为k的移动平均值,即newArray[i] = (array[i-k+1]+...+array[i])/k,稍微有些处理以使newArrayarray长度相同。我倾向于将此方法称为movingAverage,因为它返回的正是这个,但是由于它不以动词开头,所以不能这么做。我应该将此方法称为getMovingAveragegenerateMovingAverage还是calculateMovingAverage?或者这真的无关紧要?


1
在我看来,命名约定并不是一种“法律”,因此虽然你应该尝试以动词开头命名方法名称,但如果它足够描述性,我不认为你不能以名词开头(例如movingAverage就非常描述性)。不要忘记,虽然现在人们对于长方法名称并不会抱怨,但我每天都会选择movingAverage而不是computeMovingAverage。顺便说一句,我想不出一个不是通用的动词,尤其是当涉及到编程时。 - Kiril
1
即使是Java的原生方法也不完全遵循“第一个单词是动词”的惯例。例如Collection#size()Collection#toArray()。如果您认为movingAverage()足够清晰[并且没有人会认为它意味着其他东西],那么请随意使用它。 - amit
2
@amit 标准Java库不是一个好的示例,它非常不一致 - 例如,一些类具有length()方法,另一些类具有getLength()方法,甚至有一些具有同名的getter和setter方法(例如ByteBuffer.position()用于获取位置和ByteBuffer.position(int)用于设置位置 - 我会建议你不要像这样命名你的方法!) - Jesper
4
@Link 在动词中仍然有有用的信息。当你必须进行(可能很长)计算工作时,应使用computeMovingAverage - getMovingAverage则意味着仅检索已计算出的值。 - DJClayworth
@DJClayworth 非常好的观点。结合Evan的动词总结,给了我一个很好的指导方针。谢谢。 - PengOne
9个回答

46

我通常会问自己:

这个方法在做什么?

答案决定了方法应该被称为什么。当然,它完全独立于程序员。

注意:如果你不能简洁地描述这个方法在做什么,那么它可能做了太多的事情并应该被拆分。

选择你的方法的动词:

  • 执行计算:calculate
  • 检索数据:getretrieve
  • 修改数据:setchange
  • 删除数据:deleteremove
  • 转换:convert
  • 开始一个操作:startinitiate
  • 停止一个操作:stopcancel

现在,并不是所有的方法都以动词开头;但他们真的没有必要。如果你阅读到:

... myString.length();
或者
... myArray.size();

你完全知道正在发生什么-不需要动词。对于Java层次结构中较高级别的许多类方法,例如Collections、Math等,这是正确的。只要名称准确地传达了方法的作用,就可以使用。


2
另外,如果我的方法设置了一个对象的属性,我喜欢将该方法命名为populateWithPropertyName,而不是setPropertyName,因为set/get应该仅用于getter和setter。 - Jan Koester
2
很好的回答!此外,我喜欢动词“生成”来计算那些不太像“计算”所暗示的数学计算,比如从模板生成URL。 - Dawngerpony
3
为什么要用“calculate”而不是“compute”? - Yola
1
在我看来,“get”前缀意味着轻量级操作,而“calculate”等则意味着更大量的工作。 - Evan Mulawski
1
我理解你的想法。但在面向对象编程的上下文中,遵循适当的封装原则,调用方法的人不需要知道它是否轻量级。此外,正如我所解释的,太多不同的前缀会导致不一致性,至少从其他程序员使用你的API的角度来看。 - light
显示剩余9条评论

5

更新的答案。

这种类型的列表已经存在于Powershell中。要获取此列表,请运行任何Powershell终端(Windows / Linux / Mac)并运行命令Get-Verb

Verb        AliasPrefix Group          Description
----        ----------- -----          -----------
Add         a           Common         Adds a resource to a container, or attaches an item to another item
Clear       cl          Common         Removes all the resources from a container but does not delete the container
Close       cs          Common         Changes the state of a resource to make it inaccessible, unavailable, or unusable
Copy        cp          Common         Copies a resource to another name or to another container
Enter       et          Common         Specifies an action that allows the user to move into a resource
Exit        ex          Common         Sets the current environment or context to the most recently used context
Find        fd          Common         Looks for an object in a container that is unknown, implied, optional, or specified
Format      f           Common         Arranges objects in a specified form or layout
Get         g           Common         Specifies an action that retrieves a resource
Hide        h           Common         Makes a resource undetectable
Join        j           Common         Combines resources into one resource
Lock        lk          Common         Secures a resource
Move        m           Common         Moves a resource from one location to another
New         n           Common         Creates a resource
Open        op          Common         Changes the state of a resource to make it accessible, available, or usable
Optimize    om          Common         Increases the effectiveness of a resource
Push        pu          Common         Adds an item to the top of a stack
Pop         pop         Common         Removes an item from the top of a stack
Redo        re          Common         Resets a resource to the state that was undone
Remove      r           Common         Deletes a resource from a container
Rename      rn          Common         Changes the name of a resource
Reset       rs          Common         Sets a resource back to its original state
Resize      rz          Common         Changes the size of a resource
Search      sr          Common         Creates a reference to a resource in a container
Select      sc          Common         Locates a resource in a container
Set         s           Common         Replaces data on an existing resource or creates a resource that contains some data
Show        sh          Common         Makes a resource visible to the user
Skip        sk          Common         Bypasses one or more resources or points in a sequence
Split       sl          Common         Separates parts of a resource
Step        st          Common         Moves to the next point or resource in a sequence
Switch      sw          Common         Specifies an action that alternates between two resources, such as to change between two locations, responsibilities, or states
Undo        un          Common         Sets a resource to its previous state
Unlock      uk          Common         Releases a resource that was locked
Watch       wc          Common         Continually inspects or monitors a resource for changes
Connect     cc          Communications Creates a link between a source and a destination
Disconnect  dc          Communications Breaks the link between a source and a destination
Read        rd          Communications Acquires information from a source
Receive     rc          Communications Accepts information sent from a source
Send        sd          Communications Delivers information to a destination
Write       wr          Communications Adds information to a target
Backup      ba          Data           Stores data by replicating it
Checkpoint  ch          Data           Creates a snapshot of the current state of the data or of its configuration
Compare     cr          Data           Evaluates the data from one resource against the data from another resource
Compress    cm          Data           Compacts the data of a resource
Convert     cv          Data           Changes the data from one representation to another when the cmdlet supports bidirectional conversion or when the cmdlet supports conversion between multiple …
ConvertFrom cf          Data           Converts one primary type of input (the cmdlet noun indicates the input) to one or more supported output types
ConvertTo   ct          Data           Converts from one or more types of input to a primary output type (the cmdlet noun indicates the output type)
Dismount    dm          Data           Detaches a named entity from a location
Edit        ed          Data           Modifies existing data by adding or removing content
Expand      en          Data           Restores the data of a resource that has been compressed to its original state
Export      ep          Data           Encapsulates the primary input into a persistent data store, such as a file, or into an interchange format
Group       gp          Data           Arranges or associates one or more resources
Import      ip          Data           Creates a resource from data that is stored in a persistent data store (such as a file) or in an interchange format
Initialize  in          Data           Prepares a resource for use, and sets it to a default state
Limit       l           Data           Applies constraints to a resource
Merge       mg          Data           Creates a single resource from multiple resources
Mount       mt          Data           Attaches a named entity to a location
Out         o           Data           Sends data out of the environment
Publish     pb          Data           Makes a resource available to others
Restore     rr          Data           Sets a resource to a predefined state, such as a state set by Checkpoint
Save        sv          Data           Preserves data to avoid loss
Sync        sy          Data           Assures that two or more resources are in the same state
Unpublish   ub          Data           Makes a resource unavailable to others
Update      ud          Data           Brings a resource up-to-date to maintain its state, accuracy, conformance, or compliance
Debug       db          Diagnostic     Examines a resource to diagnose operational problems
Measure     ms          Diagnostic     Identifies resources that are consumed by a specified operation, or retrieves statistics about a resource
Ping        pi          Diagnostic     Use the Test verb
Repair      rp          Diagnostic     Restores a resource to a usable condition
Resolve     rv          Diagnostic     Maps a shorthand representation of a resource to a more complete representation
Test        t           Diagnostic     Verifies the operation or consistency of a resource
Trace       tr          Diagnostic     Tracks the activities of a resource
Approve     ap          Lifecycle      Confirms or agrees to the status of a resource or process
Assert      as          Lifecycle      Affirms the state of a resource
Build       bd          Lifecycle      Creates an artifact (usually a binary or document) out of some set of input files (usually source code or declarative documents)
Complete    cmp         Lifecycle      Concludes an operation
Confirm     cn          Lifecycle      Acknowledges, verifies, or validates the state of a resource or process
Deny        dn          Lifecycle      Refuses, objects, blocks, or opposes the state of a resource or process
Deploy      dp          Lifecycle      Sends an application, website, or solution to a remote target[s] in such a way that a consumer of that solution can access it after deployment is complete
Disable     d           Lifecycle      Configures a resource to an unavailable or inactive state
Enable      e           Lifecycle      Configures a resource to an available or active state
Install     is          Lifecycle      Places a resource in a location, and optionally initializes it
Invoke      i           Lifecycle      Performs an action, such as running a command or a method
Register    rg          Lifecycle      Creates an entry for a resource in a repository such as a database
Request     rq          Lifecycle      Asks for a resource or asks for permissions
Restart     rt          Lifecycle      Stops an operation and then starts it again
Resume      ru          Lifecycle      Starts an operation that has been suspended
Start       sa          Lifecycle      Initiates an operation
Stop        sp          Lifecycle      Discontinues an activity
Submit      sb          Lifecycle      Presents a resource for approval
Suspend     ss          Lifecycle      Pauses an activity
Uninstall   us          Lifecycle      Removes a resource from an indicated location
Unregister  ur          Lifecycle      Removes the entry for a resource from a repository
Wait        w           Lifecycle      Pauses an operation until a specified event occurs
Use         u           Other          Uses or includes a resource to do something
Block       bl          Security       Restricts access to a resource
Grant       gr          Security       Allows access to a resource
Protect     pt          Security       Safeguards a resource from attack or loss
Revoke      rk          Security       Specifies an action that does not allow access to a resource
Unblock     ul          Security       Removes restrictions to a resource
Unprotect   up          Security       Removes safeguards from a resource that were added to prevent it from attack or loss

你能给这个列表提供一些背景信息吗?它是从哪里获取的? - PartOfTheOhana
这是我作为标准使用的 Powershell 批处理中已批准的动词列表(当您习惯后,仅通过名称就可以清楚地了解方法的预期)。我已更新响应并提供了详细信息。 - Gravity API

4

在处理布尔方法时,不要忘记使用这些动词:“is”,“has”或“can” ,例如:isOn(),isFull()等。


1
是的。我使用的另一个前缀是"应该",例如 shouldConvertLineEndings。 - Cornel Masson

3
关于仅使用getset 方法进行属性访问的问题:应用程序编程接口(API)的用户(调用代码)不需要知道或依赖于属性是存储还是即时计算。信息隐藏的整个重点在于实现可以随时更改,只要API保持不变。信息隐藏的目的就是确保客户端代码与代码库中的实现细节隔离,从而提高灵活性和可维护性。

2
这是许多人不理解的事情。他们将 getset 视为使私有/受保护字段的行为像公共字段一样的简写,并教条地仅保留这些动词来实现这种反模式。 - light

1
我认为Java方法名不应该“以动词开头”,而是应该描述动作。这通常需要一个动词,因为动词描述动作。通常,它们是描述的重要部分(getVarsetVar意思完全不同)。偶尔,它们对描述没有任何贡献(你能想到除了get/calculate/generate之外还有什么可以操作movingAverage吗?)应该被删除。

0
(我的观点)如果对象没有状态,例如数学库,方法名称中就不需要动词。比较一下 computeSquareRoot(x) 和 getJoin(listOfStrings) 与 squareRoot(x) 和 join(listOfStrings) 的区别。

0

正如您所说,以及我们在答案中看到的那样,方法名称开头使用的动词几乎是相同的。我认为,如果花费同样的精力编写相关文档,方法将变得更加易于理解和集成 :)

阅读问题后,我也意识到我编写的大多数方法都以获取检索创建开头。因此,似乎动词选择并不那么重要。

最好的祝福


0

我认为要找到任何可能成为问题“解决方案”的东西,我们首先应该提取在选择名称时起作用的标准,例如:

  • 易读性(平凡:使用getValue而不是transferValueFromThisObjectToYou
  • 方便性(平凡:使用getCoordValue而不是)
  • 方法的语义(get与calculate不同)
  • 使用环境(在IDE中,我通常键入aaa.get_并按Ctrl + Space来检查可以从对象中获取什么)
  • 代码指南(或其他“指南”,如Java Bean约定,强制您使用某些名称)

...

然而,正如suat所说 - 最好花一些精力为您的方法编写文档。


0

我们使用方法名作为命题(如plus,minus)而不是动词(如add,subtract)。这强调了这些方法(命题)不会改变对象的值。

BigIntegerBigDecimal类没有遵守这个命名约定,这导致了许多使用错误。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接