开发者

determining which verb to use for method names in Java

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?

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?

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?


I usually ask myself:

What is this method doing?

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.

Choosing your method's verb:

  • 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();

or

... myArray.size();

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.


Do not forget to use this verbs "is, has or can" for boolean methods, such as: isOn(), isFull(), and so on.


Regarding the use of get and set methods for property accessors only: the whole point of information hiding is that the user of an API (i.e. the calling code) should not need to know or depend on whether the property is stored or calculated on the fly. The implementation should be able to change at any time, as long as the API stays the same.


Updated Answer.

This kind of list already exists in Powershell. In order to get the list, run any powershell terminal (Windows/Linux/Mac) and run the command 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


I don't think java method names should "begin with a verb", I think they should describe the action. This often requires a verb, as verbs describe actions. Usually, they are important parts of the description (getVar and setVar mean totally different things). Occasionally, they add nothing to the description (can you think of anything that would operate on movingAverage besides get/calculate/generate?) and should be dropped.


(My opinion) You don't need a verb in the method name if the object has no state, like a math-library. Compare computeSquareRoot(x) and getJoin(listOfStrings) with squareRoot(x) and join(listOfStrings).


As you said and as we can see in the answers, the verbs used at the beginning of method names are almost the same verbs. I think, if same amount of effort is spent for writing related documentation, methods become much more understandable and integrable :)

I also realized after reading the question, most of the methods I write start with get, retrieve, create. So again it seems verb selection does not matter so much.

Best


I think to find anything which could be a "solution" for the problem we should first extract criteria which play any role in choosing name, like:

  • readableness (trivial: getValue instead of transferValueFromThisObjectToYou)
  • convenience (trivial: getCoordValue instead of )
  • semantics of the method (get is not the same as calculate)
  • context of usage (in IDEs I usually type aaa.get_ and press Ctrl+Space to check what I can get from the object)
  • code guides (or other "guides" like Java Bean convention which force you to use some names)

...

However as suat said - better spend some efforts on a documentation for your methods.


We use method names as propositions (such as plus, minus) rather than verb (such as add, subtract). This emphasis the fact that these methods(propositions) don't change the value of objects.

The BigInteger and BigDecimal classes didn't obey this naming convention, and it led to many usage errors.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜