Function Names Start With A Verb

Photo by Headway on Unsplash

 

Today’s Tip is foundational to good programming.

Functions describe system behaviour. They are actions. And as such, a function’s name should describe the work it performs.

What do these functions do?

  • InvertedImage()
  • Transaction()
  • Processed()
  • TotalAmountWithTax()

These function names are a bit ambiguous.

On the other hand, these function names are more descriptive:

  • ProcessExpenses()
  • ReconcileTranactions()
  • GetCustomer()
  • BuildVehicle()

The starting verb makes all the difference. The noun is also helpful—it describes the object of the behaviour; what the action is affecting. The noun is not always necessary. Sometimes it’s obvious. A File class with an Open() method will be about opening the file.

The verb ought to be in the present tense. Simple Present Tense, e.g. CreateGame(), is more suited for naming functions than Present Continuous Tense, e.g. CreatingGame().

Are there exceptions to the rule of putting the verb first?

Yes, there are. 

Constructors: Constructors are functions setting up the initial state of an object. In many languages, the constructor name must be the name of the class:

  public class ChessGame()
  {
     // Constructor
     public ChessGame()
     { }
  }

Properties: In C#, we can have property getter and setter functions. We call these without parentheses, and they resemble data more than behaviour:

  var totalAmount = ShoppingCart.GetTotal;

or

  var totalAmount = ShoppingCart.Total;

The second option looks more natural. The first line confuses without invoking parentheses.

That’s it for today.

Please start function names with a verb.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply