determining which verb to use for method names in Java

后端 未结 7 2134
半阙折子戏
半阙折子戏 2021-01-30 23:02

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, e

7条回答
  •  鱼传尺愫
    2021-01-30 23:14

    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.

提交回复
热议问题