Skip to content
Search

Naming convention

lastmod 2022-10-11created 2016-10-2813 edits

In computer programming, a naming convention is a set of rules for choosing the character sequence to be used for identifiers which denote variables, types, functions, and other entities in source code and documentation.

  • Rules for deciding the strings that become identifier names
  • Purpose: readability, visibility, efficiency
  • May differ by project, programming language, development tool, etc.

Notation

camelCase (camel case notation)
The first letter of each word except the first is uppercase. (The first word is lowercase)
Used in Java.
PascalCase (Pascal case notation)
The first letter of every word is uppercase.
Used in Java.
under_scores, snake_case (snake case notation)
All letters are lowercase, and words are separated by underscores (_).
Used in C.
strHungarianNotation (Hungarian notation)
The type name is written first in lowercase, and then the first letter of every word is uppercase.
The notation used in the Win32 API.
kebab-case (kebab case notation)
All letters are lowercase, and words are separated by dashes (-).
Used in HTML.

Method Naming Convention

get{1}, set{1}
Hint: Java
Used for Getters1 and Setters2.
to{1}
Hint: refers to Object.toString() in Java.
Used when converting (Convert) the type of the object itself (this); put the result (return) type in {1}.
{1}With{2}
Hint: refers to NSNumber, + numberWithInteger in Objective-C.
Used when converting (Convert) a type; the source value (parameter) is {2} and the result (return) value is {1}.
Applies the meaning of with as "by using …".
Example: toStringWithFormat, toIntegerWithString
from{1}To{2}
Converts using {1} (parameter) into {2} (return value).
Applies the meaning of from A to B as "from one place (A) to another place (B)".
at{1}
Hint: refers to C++ STL Containers.
A mix of Getter and Setter. In C++ it returns a reference. Usually takes an INDEX as the parameter.
readFrom{1}, ;writeTo{1} 3
Used in classes, responsible for reading and writing. For reading (Read), it obtains from {1}; for writing (Write), it writes to {1}.
has{1}
Used to check whether something is contained.
is{1}
Checks a state (Status).
exists
Hint: Files.deleteIfExists(target); in Java
Checks whether something exists.
create{1}
Creates.

Functions returning Boolean

Using is

Variable names starting with is are probably the most common case. They can be divided into three groups depending on the word that follows.

  • is + noun
  • is + present progressive (~ing)
  • is + adjective

is + noun

Used to mean “is it (something)?”

func isDescendant(of view: UIView) -> Bool //UIView: "view의 자식인가?" 

is + present progressive (~ing)

var isExecuting: Bool { get } //Operation: "오퍼레이션의 작업이 현재 실행 중인가?"
var isPending: Bool { get } //MSMessage: "메시지가 보내지기 전 대기 중인가?"

is + adjective

This is where it can get a little confusing. Adjectives also come in two kinds.

  • Words that are adjectives themselves - opaque, readable, visible, etc.
  • Past participle forms - hidden, selected, highlighted, completed, etc.

Simply put, think of a past participle as an adjective made from a verb. Turning a verb into a past participle can change its meaning in several ways, but here you can think of it as the passive voice.

  • hide (to hide) - hidden (concealed)
  • select (to select) - selected (chosen)
  • complete (to complete) - completed (finished), and so on.

As you can see, the most common form is adding -ed to the verb, but if you don't know the past participle of the verb you want to use, look it up in a dictionary.

The UIView properties you see all the time when using UIKit are this case.

var isOpaque: Bool { get set }
var isSelected: Bool { get set }
var isHighlighted: Bool { get set }
var isHidden: Bool { get set } 

WARNING

❗Caution❗A common mistake when naming variables that start with is is using is + base form of a verb.

  • isAuthorize, isHide, isFind, etc.

For example,

var isEdit: Bool //gg

The word edit can also be used as a noun, so there is room for interpretation, but the meaning is unclear and generally not easy to understand right away. 😧 You can do better.

Changing it appropriately as below makes it easier and faster to understand.

var isEditable: Bool //편집할 수 있는가?
var isEditing: Bool //편집 중인가?
var canEdit: Bool //편집할 수 있는가? -> 다음 '조동사 용법' 섹션 참고

Added April 11

Someone pointed out that the .NET Framework has a boolean variable called DataRowView.IsEdit. According to the documentation, it is a boolean indicating ‘whether the row is in edit mode’, but a developer other than a .NET developer who doesn't know about edit mode would not have understood it at once without reading the documentation. However, if IsEdit is a variable name commonly used in the .NET Framework and it is a convention that edit means edit mode, it may be fine. After all, the very reason we care about variable names is so that other developers (or me tomorrow) can understand my code quickly and easily.

Using modal verbs

A modal verb is a verb that helps another verb, such as can, should, and will. The only thing to watch out for is that it must be written as modal verb + base form of the verb.

  • can: “can it ~?”
  • should, will: “should it ~?” or “will it ~?”

And so on.

var canBecomeFirstResponder: Bool { get } //UIResponder: first responder가 될 수 있는가?
var shouldRefreshRefetchedObjects: Bool { get set } //NSFetchRequest: 가져온 값을 refresh 할 것인가?

Using has

Bool variable names starting with has are relatively less frequent, but they come in two forms with completely different meanings, so they are useful to know.

  • has + noun
  • has + past participle

has + noun

When a noun follows has, it means “does it have ~?” has is the third-person singular of have, and the third-person singular is covered in detail in the next part.

var hasiCloudAccount: Bool { get } //CKUserIdentity: 관련된 iCloud 계정을 가지고 있는가?
var hasVideo: Bool { get set } //CXCallUpdate: 콜에 비디오가 포함되어 있는가?

has + past participle

This seems to be the least used case of all, so it's fine to skip it if you don't understand it. Besides, its meaning is almost the same as is + past participle, so there seems to be no real need to know it.

The past participle here has a different meaning from the is + past participle case earlier. has + past participle has the meaning of the present perfect, which, if you had to interpret it, means ‘something completed in the past is still maintained now’. So when used as a Bool variable, it can be read as ‘is ~ being maintained?’

var hasConnected: Bool { get } //CXCall: 콜이 연결되어 있는가?
var hasEnded: Bool { get } //CXCall: 콜이 끝났는가?

But isConnected and isEnded mean about the same. There is a subtle difference in nuance in English, but unless you're retaking the Korean college entrance exam (Suneung), I don't think you really need to know it.

Using the base form of a verb

I put this last because I think it is the ultimate level of Bool variable naming. If you can use this well, you don't need to envy native-speaker developers. (A very personal opinion)

The thing to watch out for is that the verb must be used in the third-person singular. The third-person singular is usually the base form of the verb with -s or -es added. Looking at words often used in Cocoa Touch,

  • supports: does it support ~?
  • includes: does it include ~?
  • shows: will it show ~?
  • allows: will it allow ~?
  • accepts: does it accept ~?
  • contains: does it contain ~?

and so on. Knowing just how these words are used seems enough to create rich Bool variable names.

var supportsVideo: Bool //CXProviderConfiguration: 비디오를 지원하는가?
var includesCallsInRecents: Bool //CXProviderConfiguration
var showsBackgroundLocationIndicator: Bool //CLLocationManager
var allowsEditing: Bool //CNContactViewController: 편집을 허용하는가?
var acceptsFirstResponder: Bool //NSResponder

There were also others such as returns and preserves.

var preservesSuperviewLayoutMargins: Bool //UIView
var returnsObjectsAsFaults: Bool //NSFetchRequest

However, there are cases that are not third-person singular. They seem to be fairly exceptional, so it's fine to skip this as well if you don't understand it.

//Core Location의 CLRegion 
var notifyOnEntry: Bool { get set }
var notifyOnExit: Bool { get set }

These are Bool values indicating whether to receive notifications through the delegate when the user's device exits or enters the region. The reason the base form is used here instead of notifies is that the region instance is not the one doing the notifying. If it were written as notifies, it would mean the region instance sends the notification, which is not correct. (Probably CLLocationManager sends the notification. Anyway, because the region instance is not the one doing the notifying, the third-person singular is not used.)

Why the third-person singular matters

If you compare a line of code to a sentence, the instance acting as the subject is third-person singular, so it is grammatically required, but also, not using the third-person singular breaks consistency with the Swift API Design Guidelines and can confuse people reading the code. According to the guidelines, mutating functions are named with the base form of the verb, and nonmutating functions add -ed or -ing to the verb.

Think of Array's sort() and sorted() as a familiar example.

mutating func sort() -> Void //in-place sort
func sorted() -> [Element] //정렬된 새 배열을 리턴

For example,

let overlaps: Bool = region1.overlaps(region2) //region1과 region2가 겹치는가?
region1.overlap(region2) //region1을 region2와 겹치는 부분으로 mutate
let region3 = region1.overlapping(region2) //region1과 region2가 겹치는 부분만 새로운 region 인스턴스로 리턴

Naming Bool, mutating, and nonmutating functions this way keeps them readable, grammatically correct in English, and faithful to the guidelines.

See also

Favorite site

References


  1. Accessor ↩

  2. Mutator ↩

  3. load and save have a similar meaning ↩

  4. Open_source_naming_features.pdf ↩

author Zer0 sitemap