> For the complete documentation index, see [llms.txt](https://sois-organization.gitbook.io/today-i-learned/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://sois-organization.gitbook.io/today-i-learned/clean-code/02..md).

# 주석과 포맷팅

### 주석

#### 주석이란?

* 코드의 가독성을 위해 작성하는 설명글이다.
* 주석은 코드로 인식되지 않기 때문에, 가독성을 위한 목표로 사용한다.
* 모든 내용을 주석으로 넣으면, 코드가 지저분해질 수 있다.
  * 대부분 적절한 Naming을 사용하면, 해결가능하다.
  * 네이밍으로 표현할 수 없는 영역을 주석으로 표현해야한다.

#### 주석을 사용하는 상황

1. 법적인 정보를 담을 때

   ```swift
   // Copyright (C) 2021 ...
   ```
2. 코드의 의도를 명확하게 설명할 때

   ```swift
   // throughput을 늘리기 위해 스레드를 늘린다.
   for index in 0..<10 {
       // code 
   }
   ```
3. 중요성을 강조할 때

   ```swift
   // 최종 결제 전 진행해야하는 validation 함수
   func validateBuyable(wallet: Int, price: Int) {
       // code
   }
   ```
4. 결과를 경고할 때

   함수가 런타임에서 오류를 뱉을 수 있을 때, 함수 사용 시 주의가 필요할 때 등

   ```swift
   // WARNING: API 서버가 항상 양호한지 알 수 없다.
   func connectAPIServer() {
       // code
   }
   ```

***

#### **관용적으로 사용되는 키워드**

* `TODO` : 당장은 아니지만 다음에 해야 할 때 (골뱅이로 책임자를 작성하기도 한다.)
* `FIXME` : 치명적인 에러를 발생하는 코드는 아니지만 수정해야 할 때 (시간이 없어서 나중에 고칠게)
* `XXX` : 더 생각해볼 필요가 있을 때

```swift
// TODO@jiwon: 객체의 책임 분리하기
class Store {

    // FIXME: depth 줄이기
    func sellFood() {
        for food in foods {
            for discount in dicounts {
            // code
            }
        }
    }
}
```

***

### **포맷팅**

#### **Vertical Formatting**

* 하나의 파일에 모든 코드를 넣지 않고, 개념에 맞게 파일을 나누어 관리한다.

  * 파일을 보고 내용을 예측할 수 있다.

  ```swift
  // as-is

  // Store.swift
  class FruitsStore { }
  class ComputerStore { }

  // to-be

  // FruitsStore.swift
  class FruitsStore { }

  // ComputerStore.swift
  class ComputerStore { }
  ```
* 비슷한 개념의 코드는 붙이고, 다른 개념의 코드는 Spacing으로 분리한다.

  ```swift
  func testUserBuyProduct() -> Bool {
      var user = User()                 // data 정의
      var product = Product()
                                      // **spacing 분리**
      product.setSoldOut(true)          // 실제 로직 처리
      user.get(product)

      return true                       // 처리 결과 출력
  }
  ```

#### **Horizontal Formatting**

* 한 줄에 코드를 다 넣기보단 변수 등을 활용해서 가독성 높이기

  ```swift
  // as-is
  productList += [Product("모니터"), Product("키보드"), Product("노트북")]

  // to-be
  let items = Product("모니터"), Product("키보드"), Product("노트북")
  productList += items
  ```
* 너무 긴 네이밍은 지양하기

  ```swift
  // as-is
  let userWithNameAndEmail = User("지원", "zest1923@gmail.com")

  // to-be
  let user = User("지원", "zest1923@gmail.com")
  ```
