Naming
extension List {
public mutating func remove(at position: Index) -> Element
}
employees.remove(at: x) - 좋은 예시. x가 삭제할 element의 위치를 나타내는 것이 명확하다.
employees.remove(x) - 나쁜 예시. x라는 element를 제거한다는 의미로 오인할 수 있다.
public mutating func remove(member: Element) -> Element?
allViews.remove(cancelButton) - 좋은 예시. 명확하다.
public mutating func removeElement(member: Element) -> Element?
allViews.removeElement(cancelButton) - 나쁜 예시. 함수 호출 시 Element라는 단어는 핵심 정보가 아니다.
var greeting = "Hello" - 좋은 예시. Entity의 역할을 표현하는 이름을 사용한다.
protocol ViewController {
associatedtype ContentView : View
}
class ProductionLine {
func restock(from supplier: WidgetFactory)
}
var string = "Hello" - 나쁜 예시. type 이름을 중복해서 나타낸다.
protocol ViewController {
associatedtype ViewType : View
}
class ProductionLine {
func restock(from widgetFactory: WidgetFactory)
}
x.insert(y, at: z) “x, insert y at z” (x에 y를 z위치에 삽입) // 좋은 예시
x.subViews(havingColor: y) “x's subviews having color y” (x의 subviews는 색상 y을 가짐)
x.capitalizingNouns() “x, capitalizing nouns” (x의 명사를 대문자화)
x.insert(y, position: z) // 나쁜 예시
x.subViews(color: y)
x.nounCapitalize()
AudioUnit.instantiate(
with: description,
options: [.inProcess], completionHandler: stopProgressBar) - 중요도가 낮은 arguments이므로 의도적으로 줄바꿈 한다.
✅ Bool 타입의 nonmutating 메서드/프로퍼티는 receiver (반환값)에 대한 주장 (Assertion) 형태로 이름을 지정한다. ex. x.isEmpty, line1.intersects(line2)
✅ 어떤 것인지를 설명 (describe what something is)하는 Protocol은 명사로 이름을 지정한다. ex. Collection
✅ 기능 (capability)을 설명하는 Protocol은 "able, ible, ing" suffix를 붙인다. ex. Equatable, ProgressReporting
이외 타입, 프로퍼티, 상수/변수는 명사로 이름 짓는다.
약어 (abbreviations)를 피한다. 특히 표준이 아닌 약어는 풀어쓰는 과정에서 오인될 수 있다.
동일한 기본 의미를 갖고 있거나, 특정 domain에서만 동작할 때 메서드는 base name을 공유할 수 있다.
메서드가 본질적으로 동일하게 동작하므로 base name을 공유한다. (parameter type은 다르지만)
extension Shape {
/// Returns `true` iff `other` is within the area of `self`.
func contains(_ other: Point) -> Bool { ... }
/// Returns `true` iff `other` is entirely within the area of `self`.
func contains(_ other: Shape) -> Bool { ... }
/// Returns `true` iff `other` is within the area of `self`.
func contains(_ other: LineSegment) -> Bool { ... }
}