Naming Best Practices - Part 2: Functions

Become a Subscriber

Functions are verbs

Functions usually encapsulate actions that a class will take. Maybe your class is a calculator, so you would add, subtract, and divide. These are all verbs and describe the action that the function is going to take.

class Calculator {
  func add() {}

  func subtract() {}

  func divide() {}
}

When a function returns a boolean, then we should name it like a question.

We can use verbs such as is, has, can or have.

balance.isNegative()
user.hasName()
account.canWithdraw()

Do not make the name redundant with an argument

Function names should always be an action, with as little adjective as possible. So instead of calling a method addItem(item:) we should simply call it add(item:):

// BAD
class List 
{
  func addItem(item: Item) {}
}

// GOOD
class List 
{
  fun add(item: Item) {}
}

An exception to the verb rules

If a function just returns a property and does not change state use a noun.

// BAD
account.getBalance()

// GOOD
account.balance()

Avoid abbreviations

account.bal()

Do you have any naming best practices for functions? If so tweet us @SwiftCastTV and let us know.