Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do method names always have to be verb?

Tags:

java

methods

I am new to java programming, and I am currently working on a command reading program (basically the user types in a command and my program evaluates what to do and does it). I have a separate class that contains all my commands, but they're stored as methods and aren't always using verbs as names. I understand that it is customary have methods stored as verbs. Am I using methods wrong and is there a better way to store my commands? Separate class for each command? Example of calling one of my methods:

else if (command[0].equals("math")) Commands.math();
like image 398
Simon Lynch Avatar asked Feb 07 '23 13:02

Simon Lynch


2 Answers

Do method names always have to be verb?

As far as the Java language (i.e. the Java compiler) is concerned, no. The language spec only requires you to follow some rules about what characters are used, and about contextual uniqueness.

Typical Java Style Guides don't require method names to be verbs either. But they typically recommend this. (Note that this is not something that automated style checkers check, because of the difficulty of reliably distinguishing nouns and verbs.)

I understand that it is customary have methods stored as verbs.

That is a better characterization.

This actually comes out of Object Oriented Design. A class in the design maps to a Java class, and the Java methods represent actions on the instances on the design classes. It is "natural" (and customary) to use noun-like identifiers for classes, and verb-like identifiers for methods.

But it is NOT a requirement.


In your example, you could simply address the dilemma by using "doMath" as the method name. That is a verb phrase. (The "do xyz" is a commonly used convention, albeit that it doesn't "read" very well.)

However, it seems like you could, and possibly should avoid hard-wiring the command names into the method names. Take a look at the "Command" design pattern: http://www.fluffycat.com/Java-Design-Patterns/Command/ (archived).

Design patterns are something you will need to learn in the long run, but they are possibly too much for a beginner programmer to digest.

like image 107
Stephen C Avatar answered Feb 13 '23 22:02

Stephen C


  1. Must methods be verbs? No. As long as the compiler is concerned, it doesn't matter.

  2. Should they be verbs? As a convention that will make programs easier to understand: Clearly yes.

Variables represent objects and data, so you should normally use a noun. Methods represent actions, so you should normally use a verb. There are exceptions, of course but that is the normal rule. Ideally the name of a variable or method should be enough to identify it's function in the class.

like image 39
Rober2D2 Avatar answered Feb 14 '23 00:02

Rober2D2