Swift 개발자처럼 변수 이름 짓기

1979년에 발간됐지만 여전히 프로그래밍 입문서로 유명한 Structures and Interpretation of Computer Programs의 도입부에 이런 말이 있다.

Programs should be written for people to read, and only incidentally for machines to execute.

(내맘대로 의역) 프로그램은 사람들에게 읽히기 위한 목적으로 만들어져야 하고, 우연히 컴퓨터가 실행할 수 있다면 더욱 좋다.

신입으로 입사했던 첫 해, 협업을 해보니 코드를 쓰는 시간만큼이나 읽는 시간도 엄청 많다는 걸 알게 되었다. 동료(또는 나)의 코드가 잘 읽히면 내 작업 속도가 빨라졌고 흐름을 이해하기 어려운 코드에 부딪히면 느려졌다. 그래서 그때부터 독자의 입장도 고려해야겠다는 생각을 하게 됐다. 소프트웨어의 사용자독자 양 쪽 모두에 감정 이입하는게 프로그래머의 일인 것 같다.

영어와 Naming Conventions

영어가 외국어인 우리는 컨벤션도 지켜야하고 영어도 고민해야하는 이중고에 처해 있다고 생각할수도 있지만 딱히 억울해 할 것도 없다. 영어가 모국어인 개발자가 전세계에 얼마나 될까. 미국인은 전세계 인구의 5%도 안된다. 그렇기에 완벽한 영어를 할 필요도 없고 회화 실력과는 더더욱 무관하다(해외 취업할 때는 큰 도움이 되겠지만!). 그럼에도 프로그래머 업무의 절반 이상은 이름 짓기라고 하니 알아두면 유용한 영어 문법과 스위프트 컨벤션을 일곱 가지로 분류했다.

  1. 동사의 변형
  2. 단수와 복수
  3. 타입별 Naming Conventions
  4. Bool 변수
  5. 중복 제거
  6. 스위프트의 getter
  7. fetch, request, perform 비교

#1 동사의 변형

영어에서 동사는 세 가지 형태로 사용된다. 동사원형 - 과거형 - 과거분사.
동사원형은 ‘~한다’라는 행위의 의미, 과거형은 ‘~했다’라는 과거의 의미, 과거 분사는 수동형의 의미이다. 그런데 프로그래밍을 할 때는 과거의 의미를 쓸 일이 거의 없으므로 일단은 무시해도 좋다.

동사 원형 과거형 과거 분사
request(요청하다) requested(요청했다) requested(요청된)
make(만들다) made(만들었다) made(만들어진)
hide(숨다) hid(숨었다) hidden(숨겨진)

✏️ 동사 원형

동사 원형은 크게 세 군데에 사용된다.

  • 함수 및 메서드
  • Bool 변수 (조동사 + 동사원형)
    • canBecomeFirstResponder, shouldRefresh
  • Life Cycle 관련 delegate 메서드 (조동사 + 동사원형)
    • didFinish, willAppear, didComplete

✏️ 과거 분사

동사의 의미를 형용사로 쓰고 싶을 때는 과거 분사로 변형해서 사용해야 한다.

  • 명사 수식
    • requestedData, hiddenView
  • Bool 변수
    • isHidden, isSelected

⚠️ 동사와 명사가 똑같이 생긴 단어도 있다
request(요청하다 혹은 요청), start(시작하다 혹은 시작점), play(재생하다 혹은 재생) 등

#2 단수와 복수

보통 인스턴스 하나는 단수형으로 이름 짓고 어레이 타입은 복수형으로 이름 지어준다. 복수형으로 이름 지어주는 것만으로 배열이라는 걸 알 수 있으니 특수한 경우가 아니라면 ListArray를 뒤에 붙여줄 필요는 없지 않을까 싶다.

let album: Album
let albums: [Album]

let albumList: [Album]
let albumArray: [Album]

✏️ 불규칙 복수형

복수형을 쓸 때 고려해야할 건 단어마다 복수형이 조금씩 다르다는 것이다. 대다수의 경우 -s를 붙이면 되지만 -es일때도 있고 -ies일수도 있고 새로운 단어로 바뀔 수도 있다. 안 바뀔수도..

단수 복수
view views
box boxes
half halves
category categories
child children
person people
index indices 혹은 indexes
datum data
information information

#3 타입별 Naming Conventions

좀 전에 배열 타입의 변수에 굳이 ListArray라는 타입을 명시하지 않는다고 했는데 Cocoa Touch 프레임워크 전반에 걸쳐 타입을 변수명에 명시해 주는 경우가 있다. URL, UIImage, Date, Size, Data처럼 상대적으로 raw한 데이터 타입이라면 명시해 주는 것 같고, 새로 정의한 타입이라면 써줄 필요가 없을 것 같다.

var fullSizeImageURL: URL?     //PHContentEditingInput
var thumbnailURL: URL?         //MLMediaObject
var referenceURL: URL          //SCNReferenceNode

var referenceImage: ARReferenceImage?   //ARImageAnchor
var iconImage: NSImage?                 //MLMediaGroup

var physicalSize: CGSize               //ARReferenceImage
var startDate: Date 
var adjustmentData: PHAdjustmentData?  //PHContentEditingInput

✏️ id vs Id vs ID vs identifier

프레임워크 문서를 보다가 또 한가지 발견한 것. Cocoa Touch에서는 대부분 identifier를 쓰고 별도의 타입을 쓸 때는 ID를 쓴다. 근데 이것도 절대 규칙은 아닌것 같고.. “대체로” 그렇다.

var formatIdentifier: String { get }          //PHAdjustmentData  
var identifier: String { get }                //CLRegion          
var identifier: String { get }                //MLMediaGroup 
var objectID: NSManagedObjectID { get }       //NSManagedObject
var recordID: CKRecordID { get }              //CKRecord          
var uniqueID: String? { get }                 //AVMetadataGroup 

#4 Bool 변수

Bool 변수명을 지을 때 알아두면 좋은 문법 몇 가지는 Bool 변수 이름 제대로 짓기 위한 최소한의 영어 문법에서 자세히 다뤘었고, 컨벤션적인 측면에서도 고려할 것이 몇 가지 있다.

✏️ isSelected vs selected

문법적으로만 보면 isSelectedselected 둘 다 맞다고 할 수 있으니 각 언어나 개발 플랫폼마다의 컨벤션을 따르면 되겠다. 스위프트에서는 is를 써주는 것이 컨벤션이다보니 맞춰주면 좋을 것 같다.

✏️ isEnabled vs isDisabled

Bool 타입의 경우 반대어를 써서 동일한 기능을 하는 이름을 만들 수 있다. 둘 중 뭐가 나은지 정답은 없지만 고민해볼 만한 기준은 있다. 조건문에 not 연산자를 붙이는 것 보다는 없는 것이 가독성에 조금 더 좋다. 따라서 로직이 추가되는 경우가 true가 되도록 하는 단어를 선택하면 어떨까. 또 하나는 변수의 디폴트 값이 true가 되도록 하는 것이다. UIView의 경우 ‘보여지는’ 상태가 디폴트임에도 isHidden을 쓰고 있어서 종종 뇌에 혼란이 올 때가 있다.

if isEnabled { ... }
if !isEnabled { ... }

tableView.isVisible = !items.isEmpty  //"tableView가 보일 때는 items가 비어있지 않을 때"
tableView.isHidden = items.isEmpty    //"tableView가 숨어있을 때는 items가 비어있을 때"

#5 중복 제거

의미가 중복되는 단어가 많으면 읽기 좋은 글이 아니다. 코드도 마찬가지로 불필요하게 의미가 중복되는 것을 빼버리면 간결하고 읽기 좋은 코드가 될 것이다.

struct User {
  let userID: String
}

userID는 떼어놓고 보면 의미가 명확하고 잘 지은 변수명이지만 실제 쓰일 때는 User 인스턴스와 함께 쓰일 것이기 때문에 굳이 ‘user’라는 의미를 포함시키지 않아도 된다. identifier라고만 해줘도 충분하다.

let id = user.userID
let id = user.identifier

함수나 메서드 이름을 지을 때도 마찬가지다.

struct ImageDownloader {
  func downloadImage(from url: URL) { ... }
}

downloadImage(from:)도 잘 지은 것 처럼 보이지만 실제로 사용해보면 image와 download라는 단어가 불필요하게 중복된다.

let image = imageDownloader.downloadImage(from: url)

메서드가 사용될 때의 인스턴스 이름까지 고려해서 아래와 같이 중복을 제거해볼 수 있을 것이다.

let image = imageDownloader.fetch(from: url)
let image = imageManager.download(from: url)

등등.

#6 스위프트의 getter

스위프트에서 어떤 인스턴스를 리턴하는 함수나 메서드에 get을 쓰지 않는다. get 없이 바로 타입 이름(명사)으로 시작하면 된다.

func date(from string: String) -> Date?
func anchor(for node: SCNNode) -> ARAnchor?                          
func distance(from location: CLLocation) -> CLLocationDistance        
func track(withTrackID trackID: CMPersistentTrackID) -> AVAssetTrack? 

#7 fetch, request, perform

우리는 데이터를 어디선가 가져오는 함수를 자주 작성하게 된다. 디스크에 저장되어있는 이미지, 리모트 서버에 있는 유저 db, 메모리 캐싱되어 있는 데이터 등등. 그럴때 위와 비슷한 동사들을 사용한다. 가져오다, 요청하다, 수행하다 등 사전적인 의미는 크게 다르지 않지만 iOS 프레임워크들을 찬찬히 읽어보니 쓰이는 경우가 명확히 구분되어 있었다.

✏️ 결과를 바로 리턴하는 fetch

//PHAsset - Photos Framework
class func fetchAssets(withLocalIdentifiers identifiers: [String], options: PHFetchOptions?) -> PHFetchResult<PHAsset>

//PHAssetCollection - Photos Framework
class func fetchAssets(in assetCollection: PHAssetCollection, options: PHFetchOptions?) -> PHFetchResult<PHAsset>

//NSManagedObjectContext - Core Data
func fetch<T>(_ request: NSFetchRequest<T>) throws -> [T] where T : NSFetchRequestResult

fetch를 쓴 함수는 결과물을 바로 리턴해준다. 오래 걸리지 않는 동기적 작업이라는 것이다. 결과가 0개인 경우를 제외하곤 요청이 실패하지 않는 종류의 작업이다. 강아지가 공을 물어오는 놀이를 영어로 “play fetch”라고 하는데, 공을 무조건 물어오는 강아지의 모습을 연상하며 사용하면 되지 않을까


(playing fetch)

✏️ 유저에게 요청하거나 작업이 실패할 수 있을 때 request

//PHImageManager
func requestImage(for asset: PHAsset, targetSize: CGSize, contentMode: PHImageContentMode, options: PHImageRequestOptions?, resultHandler: @escaping (UIImage?, [AnyHashable : Any]?) -> Void) -> PHImageRequestID

//PHAssetResourceManager
func requestData(for resource: PHAssetResource, options: PHAssetResourceRequestOptions?, dataReceivedHandler handler: @escaping (Data) -> Void, completionHandler: @escaping (Error?) -> Void) -> PHAssetResourceDataRequestID

//CLLocationManager
func requestAlwaysAuthorization()
func requestLocation()

//MLMediaLibrary
class func requestAuthorization(_ handler: @escaping (MPMediaLibraryAuthorizationStatus) -> Void)

반면에 request를 쓰는 함수들은 비동기 작업이어서 handler를 받고 있거나 delegate 콜백으로 결과를 전달해준다. 그리고 결과 타입이 옵셔널이고 실패했을 경우 실패 이유를 알수 있는 Error 객체도 있는걸로 보아 요청이 실패할 수도 있다는 걸 알 수 있다. 또한 유저에게 특정 권한을 요청하는 메서드는 모두 request로 시작한다. 이것을 보면 request는 실패할 수 있는 작업이거나 누군가가 요청을 거절 할 수도 있을 때 사용하면 좋을 것 같다.

✏️ 작업의 단위가 클로져나 Request로 래핑 되어있으면 perform 혹은 execute

//VNImageRequestHandler
func perform(_ requests: [VNRequest]) throws

//PHAssetResourceManager
func performChanges(_ changeBlock: @escaping () -> Void, completionHandler: ((Bool, Error?) -> Void)? = nil)

//NSManagedObjectContext
func perform(_ block: @escaping () -> Void)

//CNContactStore
func execute(_ saveRequest: CNSaveRequest) throws

//NSFetchRequest
func execute() throws -> [ResultType]

perform이나 execute은 파라미터로 Request 객체나 클로져를 받는 경우이다.

덧붙이는 말

스위프트에 특화된 내용이기 때문에 다른 언어나 플랫폼은 또 다른 컨벤션을 가지고 있고 읽기 좋은 코드의 기준도 다르다. 예를 들어 자바에서는 get을 써서 getter를 만드는 것이 컨벤션이고, 또 안드로이드의 ViewisHidden이 아니라 VISIBLE, INVISIBLE, GONE을 쓴다. 이처럼 프로그래밍 언어에 따라, 플랫폼에 따라 달라진다.

마무리

최적의 알고리즘을 짜기 위해 고민하는 것 만큼이나 그 코드를 영어로 잘 표현하는 것도 중요한 일인 것 같다. 그러면 대체 어떤 단어를 쓰고 어떻게 이름 지어야 좋은 걸까? 먼저 동의어 사전을 활용해 다양한 단어를 찾아보고 뜻을 알아보자. 그리고, ‘읽기 좋은 코드가 좋은 코드다(한빛미디어)‘의 저자는 좋은 코드를 많이 읽어보라고 한다. 또 표준 라이브러리와 프레임워크 문서를 하루에 15분씩이라도 시간을 할애하여 읽어보면 좋다고 한다. 그 조언대로 스위프트와 iOS 공식 문서를 앞에서부터 순서대로 읽어봤는데 주위에도 강력 추천하고 싶다.

[발표 동영상 - NAVER Engineering TV]

이 글의 초안을 읽어준 이승원, 김결, 강한용, 김영에게 고마움을 전합니다.

Tags: naming variables, iOS, english grammar, swift conventions  

google/promises를 활용한 스위프트 비동기 프로그래밍과 에러 핸들링

Background

올해 1~2월 즈음 우연히 google/promises를 알게 되었는데 소개 글과 샘플 코드 몇 줄을 보고 나서 ‘이건 꼭 써봐야겠다’는 생각이 들었다. 뭘 하는 프레임워크인지는 깃헙에 잘 소개되어 있어 상세한 설명은 생략하지만 한 줄 요약을 하자면 비동기 작업에 대한 결과를 completion handler로 처리하는 iOS의 특성에 기인하는 nested closures 문제를 해소할 수 있다. 여기에 덤으로 에러 처리까지 깔끔해진다.

Promises를 보자마자 써봐야겠다고 느꼈던 이유는 그 전부터 내 코드에서 시도하고자 했던 것들이 있었는데 이 라이브러리가 그걸 달성할 수 있게 해줄것 같았기 때문이다.

  • 사이드 이펙트 없는 함수들의 체이닝
  • 유저에게 의미있는 에러 핸들링
  • 최소한의 튜닝(디펜던시)

이런 작은 목표들은 작업의 흐름을 읽기 쉬운 코드를 짜고 유저에게 더 나은 경험을 주고자 하는 최종적인 목표에 도움이 될 것이라 생각했다.

Chaining functions w/o side effects

2016년 D2 iOS 오픈세미나에서 발표했던 걸 계기로 파파고와 웨일 브라우저를 개발한 팀의 리더님을 알게되어 그 팀에서 단기로 프로젝트를 했던 적이 있다. 멘토님에게서 배운 여러가지 중 가장 기억에 남고 지금도 코딩하면서 매일 실천하기 위해 노력하는 것은 함수는 10줄을 넘기지 않는다이다. 자극적으로 들릴 수도 있지만 본질적으로 함수는 하나의 작업만 하도록 짜라는 강령으로 이해했다. 10줄 이내로 짜려는 노력을 하다보면 계속해서 함수는 작은 기능 단위로 쪼개지고 나는 객체 간의 관계를 설계하는데 고민하는 시간이 늘게 된다. 더 나아가 side effect가 없는 함수들을 체이닝 하면 코드가 쉽게 읽히고 수정이 용이해진다는 장점이 있다. 특히 스위프트의 map, flatMap, compactMap, filter 등의 메서드와 함께 쓸 때 빛을 발한다. Promises에서는 then, always, validate 등으로 함수를 체이닝할 수 있다.

예시:

extension CNContact {
  var mainPhoneNumber: String? {
    return phoneNumbers.map { $0.value.stringValue }
                        .filter(prefixValidater)
                        .map(replaceKoreanCountryCode)
                        .map(removeNonNumerics)
                        .filter { $0.isPhoneNumber && $0.count == 11}
                        .first
  }

  private func prefixValidater(_ target: String) -> Bool { ... }
  private func replaceKoreanCountryCode(_ digits: String) -> String { ... }
  private func removeNonNumerics(_ digits: String) -> String { ... }
}

Conveying meaningful error messages to users

모바일 앱 개발을 몇 년 하다보니 어떻게 에러 핸들링을 잘 할 수 있을까 하는 갈증이 생겼다. 모바일 앱에서 가장 많이 일어나는 작업의 단계는 유저 인터랙션 👉 요청을 처리하기 위한 일련의 작업 👉 화면에 결과 보여주기 인데 일련의 작업을 처리하다보면 다양한 에러가 발생할 수 있다. 데이터가 변질됐거나, 네트워크가 불안정하거나, 서버가 다운됐거나, 권한이 없다거나 하는 등. 이때 단순히 “요청이 실패했습니다”라는 의미없는 메시지보다는 에러의 원인을 유저에게 알리는 것이 사용자 경험 측면에서 월등히 좋다. NSError의 localizedDescription을 활용하거나 스위프트에서는 Error 혹은 LocalizedError 프로토콜을 사용할 수 있다. Promises에서는 여러 연속된 비동기 작업 도중 발생한 에러를 최종 단계에서 통일성 있게 전달 받을 수 있고, 심지어 recover로 복구할 기회도 있다.

이런 에러 메시지를 보여줄 것인가?

아니면 실질적으로 유저에게 도움이 되는 메시지를 보여줄 것인가?

Minimizing dependencies

스탠다드 라이브러리를 감싼 무슨무슨 ~Kit을 쓰는 것에 대한 미묘한 거부감이 있다. 아이폰도 케이스 없이 보호 필름만 붙이고 다니는 성격이라 그런지 프로젝트 한 두군데에서만 쓰기 위해, 혹은 필요한 1만큼의 기능을 가져다 쓰기 위해 10 크기의 라이브러리를 코코아팟에 이것저것 추가하는 것이 무척 꺼려진다. 오토레이아웃도 별도 라이브러리 없이 쓰고 있고 한때 관심을 가졌던 Rx도 공부하다가 결국 과도한 튜닝을 하는 것 같아 도외시했다. 튜닝의 끝은 순정이라고, 순정을 선호하는 입장에서 Promises는 다른 유사 라이브러리보다 GCD를 더 가볍게 감쌌기 때문에 성능에서 앞서고 학습 비용도 적은 것 같다.

Adopting Promises to Your Project

Promises를 도입하겠다고 해서 당장 프로젝트 전체를 뜯어고치지 않아도 되기 때문에 실무에서 차근차근 적용해보기에도 좋다. 보통 작업의 특성별로 담당 클래스가 있을텐데(e.g. 로그인매니저, 이미지다운로더 클래스 등과 같은) 이런 클래스 한 두개만 우선적으로 적용하며 맛보기를 해봐도 충분하다. 또한 wrap을 쓰면 기존에 있던 코드를 손댈 필요도 없이 코드 몇 줄로 Promises식 비동기 함수를 만들 수도 있다.

기존에 completion handler를 파라미터로 받던 함수:

func data(from url: URL, completion: @escaping (Data?, Error?) -> Void)

Promise 객체를 리턴하도록 수정한 비동기 함수:

func data(from url: URL) -> Promise<Data>

그러면 함수 내부에서 Promise 객체를 생성하여 리턴해준 후, fulfill된/될 결과값을 가지고 추가적인 작업을 해주면 된다.

let url = ...
data(from: url).then { data in
  //data로 추가 작업
}.catch { error in
  //error 처리
}

더 다채로운 활용법은 문서에 간단명료하게 잘 설명되어 있다!

Use Cases

그동안 사용해보면서 시행착오를 거쳐 습득한 몇 가지 유즈케이스 및 주의사항을 정리했다.

Partial Application 기법

Promises 파이프라인의 가독성과 함수 재활용성을 높이기 위해 partial application 기법을 활용하는 방법을 소개한다. map, forEach 등의 higher order function들을 사용하고 있었다면 아마 써본적이 있을 확률이 높다.

API 서버에 로그인하여 access token을 받아오는 작업은 로그인 기반의 서비스에서 빠질 수 없는 작업이다. 가상의 로그인 단계는 다음과 같다. 회원가입 👉 로그인 👉 엑세스 토큰 획득. 하지만 이미 회원가입이 되어 있는 유저라면 회원가입에 실패하게 된다. Promises에서는 실패했을때 recover를 사용해서 실패를 복구할 기회가 있다. 그래서 만약 회원가입 실패의 원인이 duplicate user라면 로그인을 시도한다.

Promises 코드:

typealias MyAccessToken = String

func retrieveAccessToken(with naverToken: String) -> Promise<MyAccessToken> {
  return requestSignUp(with: naverToken)
         .then(signIn(with: naverToken))
         .recover(onError(with: naverToken))
}

//Async Server API calls
func requestSignUp(with naverToken: String) -> Promise<SignUpResponse> { ... }
func requestSignIn(with naverToken: String) -> Promise<MyAccessToken> { ... }

//partially applied functions
func signIn(with naverToken: String) -> (SignUpResponse) -> Promise<MyAccessToken> {
  return { _ in requestSignIn(with: naverToken) }
}

func onError(with naverToken:String) -> (Error) -> Promise<MyAccessToken> {
  return { error in
    switch error {
    case SignUpError.duplicateUser:
      return requestSignIn(with: naverToken)
    default:
      return Promise(error)
    }
  }
}

signIn(with:)onError(with:)는 각각 SignUpResponse와 Error 파라미터를 나중에 전달 받도록 짠 partially applied functions이다. 이런 식으로 체이닝을 할 때 클로져를 바로 쓰지 않고 partial application을 활용하여 기존의 API 관련 함수들을 재활용함과 동시에 비동기 작업 파이프라인을 훨씬 읽기 쉽게 만들었다.

단순 체이닝으로 불가능한 작업은 await으로

await은 여러 비동기 작업으로부터 얻은 결과들을 혼합해서 사용해야 할때 유용하다.

예를 들어, 썸네일 이미지에 대한 url을 가지고 UIImage와 해당 이미지의 대표 UIColor 추출해 화면에 그려야 하는 작업이 있다고 가정해본다. 정리하면 URL을 UIImage로 변환 👉 UIImage에서 UIColor 추출 👉 UIImage, UIColor를 가지고 화면에 썸네일 생성 해야했는데 이 작업은 then 체이닝만으로는 구현하기 어려웠고 이를 await으로 해결했다. 또한 이 방식은 비동기 작업을 동기적인 코드처럼 쓰고 싶을 때 사용해도 된다.

Promises 코드:

typealias ThumbnailData = (image: UIImage, color: UIColor)

func thumbnailData(from url: URL) -> Promise<ThumbnailData> {
  return Promise<ThumbnailData>(on: queue) { //queue는 백그라운드 DispatchQueue
    let image = try await(image(from: url))
    let color = try await(dominantColor(from: image))

    return (image: image, color: color)
  }
}

//Async functions
func image(from url: URL) -> Promise<UIImage> { ... }
func dominantColor(from image: UIImage) -> Promise<UIColor> { ... }

활용한 부분:

let cell: MyTableViewCell = ...
let myDatum = data[indexPath.row]
let url: URL = myDatum.imageURL

thumbnailData(from: url).then { result in
  cell.imageView.image = result.image
  cell.dominantColorView.backgroundColor = result.color
}

추가적으로 Promises 사용 전 꼭 알아두면 좋은 내용으로는,

정도가 있다.

Wrap Up

iOS 개발을 하면서 한번이라도 completion handler 방식의 비동기 프로그래밍에 아쉬움을 느껴봤거나 Rx는 나의 필요 이상으로 너무 방대하다는 생각이 든 적이 있다면 한번 시도해보길 추천한다. google/promises는 최소한의 코드 변형으로 비동기 코드를 유연하게 하고, 가독성을 높이고, 적은 학습 비용으로 여러가지 시도해볼 수 있는 확장성 있는 좋은 프레임워크인 것 같다.

Tags: swift, promises, async programming, error handling  

Swift Asynchronous Programming and Error Handling Using Google/Promises

Background

I happened to find out about google/promises around January or February this year. I saw the introduction and a few lines of the sample code, and thought, ‘I need to try using it’. What kind of framework is well-introduced in GitHub, so I won’t explain it in much detail here, but if I summarize it in one line, I can say it can solve the nested closures problem caused by the iOs’s characteristics of processing the results of the asynchronous tasks using a completion handler. On top of that, the error handling becomes clean as a bonus.

The reason why I thought I should use Promises as soon I found out about it was because I thought this library would help me achieve the things that I wanted to try with my codes before.

  • Chaining of functions without side effects
  • Error handling that is meaningful to the user
  • Minimal tuning(dependency)

I thought these small goals would help me reach the final goal of creating code that’s easy to read and giving the users a better experience.

Chaining functions w/o side effects

After the announcement at the 2016 D2 iOS Open Seminar, I got to know the leader of the team that developed Papago and Whale Browser and worked with that team for a short term. The most memorable thing I learned from my mentor and the thing I’m still working to practice every day while coding is that a function shouldn’t exceed 10 lines. It may sound provocative, but in essence, I understood it as a rule that a function needs to be designed to carry out only one task.

If you try to write it in less than 10 lines, the function continues to break down into smaller features and it gives you more time to think about designing relationships between each object. Furthermore, chaining functions without side effects has the advantage that code is easily read and modified. This especially shines when used with Swift’s methods such as map, flatMap, compactMap, filter, etc.

In Promises, functions can be chained with then, always, validate, etc.

Example:

extension CNContact {
  var mainPhoneNumber: String? {
    return phoneNumbers.map { $0.value.stringValue }
                        .filter(prefixValidater)
                        .map(replaceKoreanCountryCode)
                        .map(removeNonNumerics)
                        .filter { $0.isPhoneNumber && $0.count == 11}
                        .first
  }

  private func prefixValidater(_ target: String) -> Bool { ... }
  private func replaceKoreanCountryCode(_ digits: String) -> String { ... }
  private func removeNonNumerics(_ digits: String) -> String { ... }
}

Conveying meaningful error messages to users

After several years of developing mobile apps, I had a thirst for how to handle errors well. The step that happens most frequently in a mobile app is user interaction 👉 a series of tasks to process the request 👉 displaying the results on the screen. As a series of tasks are being processed, various errors may occur. The data may be corrupted, the network may be unstable, the server may be down, or you may have no permission to access it. In this case, rather than simply showing a meaningless message that says, “Request Failure,” letting the user know the cause of failure is much better in terms of user experience. You can make use of localizedDescription of NSError, or Error or LocalizedError protocol on Swift. In Promises, you can uniformly receive errors that occurred during several consecutive asynchronous operations in the final stage, and there’s even an opportunity to recover them.

Are you going to show an error message like this?

Or are you going to show a message that is actually helpful to the user?

Minimizing dependencies

There’s a subtle repulsion to using some ~Kits that go around the standard library. I’m the person who goes around with no protection film on my iPhone, so I’m very reluctant to add a 10-size library just for a 1-size feature, and other things on CocoaPods just to use them in one or two projects.

I’m using auto layouts without a separate library, and I was once interested in Rx so I used to study it, but eventually neglected it because it seemed like over-customizing. As they say, the end of customizing is original. Because I prefer the original, I think Promises goes ahead in performance because it wraps GCDs lighter than other similar libraries, and learning it costs less as well.

Adopting Promises to Your Project

Because you’re introducing Promises, you don’t have to redo the whole project. It’s good to apply it step by step in practical work. Usually, there is a class in charge of each characteristic of a task. (e.g. login manager, image downloader class, etc.) It’s enough to apply it only in one or two of these classes first. If you use the wrap, you don’t have to change the existing codes and create an asynchronous function in a Promise style with only a few lines of code.

A function that originally received a completion handler as a parameter:

func data(from url: URL, completion: @escaping (Data?, Error?) -> Void)

An asynchronous function that was modified to return a Promise object:

func data(from url: URL) -> Promise<Data>

Then create a Promise object and return it within the function, and carry out additional tasks with the resulting values that are/will be fulfilled.

let url = ...
data(from: url).then { data in
  //additional task using data
}.catch { error in
  //error handling
}

Additional uses are clearly and concisely explained in the document.

Use Cases

I’ve organized some use cases and precautions that I’ve learned through trial and error while using Promises.

Partial Application 기법

I’d like to introduce how to apply the partial application technique to increase the readability of the Promises pipeline and function reusability. There’s a high probability that you have tried using it if you were using higher-order functions such as map, forEach, etc.

The task of acquiring the access token after logging in to the API server is an indispensable task in log-in based services. The virtual login steps are as follows. Sign up 👉 Log in 👉 acquire an access token. But if you’re already registered, you’ll fail to sign up. There is a chance to recover from the failure in Promises by using recover. So if the cause of failure to sign in is a duplicate user, attempt to log in.

Promises Code:

typealias MyAccessToken = String

func retrieveAccessToken(with naverToken: String) -> Promise<MyAccessToken> {
  return requestSignUp(with: naverToken)
         .then(signIn(with: naverToken))
         .recover(onError(with: naverToken))
}

//Async Server API calls
func requestSignUp(with naverToken: String) -> Promise<SignUpResponse> { ... }
func requestSignIn(with naverToken: String) -> Promise<MyAccessToken> { ... }

//partially applied functions
func signIn(with naverToken: String) -> (SignUpResponse) -> Promise<MyAccessToken> {
  return { _ in requestSignIn(with: naverToken) }
}

func onError(with naverToken:String) -> (Error) -> Promise<MyAccessToken> {
  return { error in
    switch error {
    case SignUpError.duplicateUser:
      return requestSignIn(with: naverToken)
    default:
      return Promise(error)
    }
  }
}

signIn(with:) and onError(with:) are partially applied functions that are designed to receive the SignUpResponse and Error parameters later. When chaining this way, I did not use the closure right away and used a partial application to reuse the existing API-related functions and at the same time, made the asynchronous task pipeline much easier to read.

The task that is impossible with simple chaining is await.

Await is useful when it needs to be used with combined results from several asynchronous tasks.

For example, suppose there’s a task that requires the UIImage and its major UIColor to be extracted and drawn on the screen using the URL for the thumbnail image. In short, convert the URL to UIImage 👉 extract UIColor from the UIImage 👉 create a thumbnail using UIImage and UIColor on the screen. This task was difficult to implement with then chaining alone, and it was resolved with await. This method can be used when you want to use an asynchronous task like a synchronous code.

Promises Code:

typealias ThumbnailData = (image: UIImage, color: UIColor)

func thumbnailData(from url: URL) -> Promise<ThumbnailData> {
  return Promise<ThumbnailData>(on: queue) { //queue는 백그라운드 DispatchQueue
    let image = try await(image(from: url))
    let color = try await(dominantColor(from: image))

    return (image: image, color: color)
  }
}

//Async functions
func image(from url: URL) -> Promise<UIImage> { ... }
func dominantColor(from image: UIImage) -> Promise<UIColor> { ... }

Applied Code:

let cell: MyTableViewCell = ...
let myDatum = data[indexPath.row]
let url: URL = myDatum.imageURL

thumbnailData(from: url).then { result in
  cell.imageView.image = result.image
  cell.dominantColorView.backgroundColor = result.color
}

Additionally, something important to note before using Promises,

Wrap Up

I recommend you to try this if you’ve had any regrets with asynchronous programming done in a completion handler method or if you’ve ever thought that Rx is way too vast for you while working in iOS development. I think Google/Promises is a good framework that makes asynchronous code flexible with minimal code modifications, increases readability, and is able to try many things with a small learning cost.

Tags: swift, promises, async programming, error handling