슈퍼앱 운영을 위한 확장성 높은 앱 아키텍처 구축
🧑💻 강의 링크
모바일 개발자에게 확장성(scalability)이란
모바일 팀과 앱의 규모가 계속 커져도 사용자 경험과 개발자 경험 모두를 안정적으로 유지하는 것이라고 생각합니다.
개발자의 기술력은 개발 과정에서 발생하는 병목 현상을 얼마나 잘 처리하는지에서 보여지죠. 서버의 경우에는 많은 사용자가 몰릴 때 병목 현상이 발생하지만, 모바일의 경우에는 하나의 프로그램에 다수의 개발자들의 코드가 몰릴 때 병목이 발생한다고 볼 수 있습니다.
관련글: 모바일 개발자에게 scalability란 뭘까
강의 내용
1부. 코드 레벨 아키텍처: 재사용 가능한 코드를 만드는 스킬
객체를 작게 만들고, 작은 객체를 조합해서 복잡한 기능으로 합치는 것이 아키텍처의 시작입니다. Massive View Controller, Massive View Model, Massive Interactor를 벗어나게 해주는건 또다른 아키텍처가 아니라 composition 활용 능력입니다. Composition이 강력한 아키텍처 프레임워크 RIBs를 기반으로 미니 슈퍼앱을 만들어봅니다.
관련1: 스위프트로 다시보는 객체지향 프로그래밍: 피해야할 코딩 습관
관련2: 개발자와 라면 조리법
관련3: google/promises를 활용한 스위프트 비동기 프로그래밍과 에러 핸들링
2부. 모듈 레벨 아키텍처: 유지 보수와 개발 속도를 고려하는 모듈화
‘느슨하게 결합된 모듈 구조’는 ‘확장성 있는 아키텍처’와 같은 말이나 다름없습니다. 200명의 iOS 앱 개발자가 기여하는 슈퍼앱 그랩, 약 75명이 기여하는 에어비엔비 같은 회사의 개발자들이 생산성을 지킬 수 있는 방법입니다. 왜 모듈화를 하면 빌드 시간이 줄어들고 생산성이 오르는지 원리를 알아보고 실습을 통해 미니 슈퍼앱에 적용해봅니다.
관련1: 모바일 앱의 느슨한 결합
관련2: Sourcery 개발자로부터 배우는 모바일 아키텍처와 개발자 경험
3부. 자동화 테스팅
테스트를 처음 시작하기 어려운 이유는 레거시 코드가 테스트 불가능한 구조로 짜여져 있기 때문이라고 생각합니다. 하지만 실습에서 짜는 코드는 99% 테스트 가능한 코드입니다. 테스트 가능한 코드의 특징을 한번이라도 익히고 직접 테스트를 작성해보면 레거시 코드에 도입하기도 쉽습니다. 유닛테스트, 스냅샷테스트, UI테스트, 통합테스트를 작성해봅니다.
관련1: 테스트와 좋은 설계의 관계, 그리고 나쁜 설계의 영향
관련2: 테스트 코드 작성하면 좋은 점
관련3: uber/RIBs 유닛 테스트 짜기
관련4: XCTest 소요시간 단축하기
4부. 확장성 있는 인프라: 코드만으로 해결할 수 없는 문제들
확장성 있는 아키텍처는 코드 뿐 아니라 개발 프로세스도 뒷받침해줘야 합니다. 피쳐플래그와 품질 모니터링을 도입해서 얻을 수 있는 것들과 제가 경험해본 좋은 개발 문화 사례를 공유합니다.
관련1: 앱 안정성을 향한 끊임없는 여정
관련2: 팀워크
관련3: 개인과 팀이 성장하는 모바일 개발 환경
Tags: app architecture, super app, fastcampus
모바일 앱의 느슨한 결합
프로그래밍은 제대로 동작하는 소프트웨어를 효율적으로 만들어내는 일이고, 그걸 잘하려면 유지 보수가 쉬운 코드를 만들어야 한다. 그리고 유지 보수하기 좋은 코드를 만드는 매우 효과적인 방법은 객체를 느슨하게 결합(loose coupling)하는 것이다. Gang of Four는 디자인 패턴에서 다음과 같이 말했다.
Program to an interface, not an implementation.
구현에 의존하지 않고 인터페이스에 의존하는 결합 관계를 느슨하다고 한다. 느슨하게 결합된 코드는 확장이 용이하고 유지보수하기 훨씬 수월하다. 프로그램이 커지고 복잡해져도 관리할 수 있다.
느슨하게 결합된 코드를 짤 수 있게 해주는 소프트웨어 디자인 원칙이자 패턴을 의존성 주입이라고 한다. 강하게 결합된(tightly coupled) 코드에는 없는 요소기 때문에 이런 추가적인 요소가 왜 필요한지 납득하려면 느슨하게 결합된 코드의 장점을 먼저 이해해야 한다.
1. 늦은 연결(Late Binding)이 가능하다.
코드를 다시 컴파일하지 않고도 구현체를 갈아 끼울 수 있다. 딱 맞아 떨어지는 예시는 아니지만 모바일 앱 관점에서 보면 운영체제가 업데이트되거나 애플/안드로이드가 제공하는 프레임워크가 업데이트됐을 때 굳이 앱을 새로 배포하지 않아도 유저들은 새로운 기능을 경험할 수 있는 원리와 비슷하다.
하지만 이건 모바일 앱 개발자 입장에서는 와닿지 않는다. 왜냐하면 앱은 개발자가 정의하고 구현한 환경에서만 실행되기 때문에 사실상 구현체를 갈아끼울 일이 없다. 가령 데이터베이스가 필요한 앱을 만들때 앱 개발자 본인이 도입한 데이터베이스 외의 다른 데이터베이스를 쓰는 환경에서 내 앱이 실행될 거라는 가정과 고려 자체를 할 필요가 없다. 따라서 늦은 연결은 모바일 개발자가 누릴 수 있는 이점이라고 보기 어렵다. 하지만 느슨한 결합의 장점은 이게 전부가 아니다.
2. 확장과 재사용이 쉽다.
앱은 유저에 맞춰 요구사항이 바뀌고 사업에 맞춰 계속 진화한다. 클래스/모듈을 느슨하게 결합하면 새로운 기능을 개발하거나 기존 기능을 수정하고 확장하는게 쉬워진다. 느슨하게 결합된 코드는 확장에는 열려있고 수정에는 닫혀있게 된다. 느슨하게 결합된 코드에서는 객체를 조립하는 지점(composition root)이 따로 있고 여기서 실제 구현체를 생성해서 주입하기 때문에 인터페이스를 사용하고 있는 쪽 코드는 바뀔 필요가 없다.
예를 들어 앱에 결제 기능이 있을 때, 상품 쪽 코드가 결제 관련 인터페이스에 의존하고 있다면 결제 플로우를 개선하거나 개편해야할 때 결제 기능을 가져다 쓰는 상품 쪽 코드는 아예 건드릴 필요가 없다. 좀 더 일반화해서 A/B 테스팅을 생각해볼 수 있다. 동일한 기능을 여러 종류의 방식으로 제공해야할 때, 그 기능을 호출하는 쪽의 코드 수정 없이도 새 기능을 추가하거나 뺄 수 있다.
3. 병렬로 개발 할 수 있다.
프로젝트와 팀이 커지면 한 코드베이스에 여러 개발자가 병렬적으로 일하게 된다. 코드가 느슨하게 결합되어 있으면 개발자들이 여러 모듈을 동시에 개발하기 쉽다.
그랩 모바일 개발 팀은 100+명의 iOS 개발자가 모빌리티, 푸드, 페이먼트, CX 등 10개 미만의 큰 TF(Tech Family)로 나뉘어져 있다. 각 팀은 다른 팀이 만드는 기능(실시간 채팅, 결제, 잔액 조회, 리워드 포인트, 유저 정보/인증 등등)을 활용하면서도 느슨하게 결합된 코드 덕분에 ‘슈퍼앱’을 동시에 개발할 수 있다.
4. 유지 보수가 쉽다.
클래스와 모듈의 경계와 역할이 명확하게 구분되어 있는 코드는 유지 보수하기 쉽다. 신규 기능을 개발할 때 어디를 수정하면 될지 빨리 파악할 수 있고 영향 범위를 쉽게 볼 수 있다. 하나의 역할만 하는 클래스나 모듈로 결합된 코드에선 디버깅도 덜 힘들다. 역할과 범위가 잘 분리되어 있으면 버그를 일으켰을 만한 지점을 비교적 잘 좁힐 수 있기 때문이다.
5. 테스트가 용이하다.
정확히 말하면 유닛 테스트가 용이하다. 유닛 테스트를 하려면 테스트 대상을 의존성으로부터 고립시킬 수 있어야 한다. 객체끼리 느슨하게 결합되어 있으면 테스트 대역으로 치환하기가 쉽다.
유닛 테스트의 필요성이나 코드 구조의 테스트 용이성을 높게 평가하지 않는 사람도 있을거다. Jetbrain의 2021년 개발자 설문을 보면 62%의 스위프트/Obj-C 개발자가 유닛 테스트를 작성하지 않는다고 한다. 그러나 자동화된 테스트의 이점을 한번이라도 경험해보면 (과장 조금 보태서) 테스트 코드를 안짜던 시절로 돌아갈 수 없다.
유닛 테스트는 상당한 테스트 업무를 자동화할 수 있게 해준다. 그랩에선 100+ 여 명의 개발자가 한달에도 수십 만 줄의 앱 코드를 생산하고 있는데, 유닛 테스트 없이 새로운 코드와 기존 코드의 동작을 전부 수동으로 검사하기란 실질적으로 불가능하다. 그랩에서 우리 팀이 새로 만들어졌을 때 만해도 코드 커버리지가 낮았지만, 1년 넘게 테스트를 추가한 결과 실제로 회귀 버그와 중대 버그의 수가 눈에 띄게 줄었다.
마무리
엉클밥에 의하면 객체 지향 언어가 개발자에게 쥐어준 가장 강력한 무기는 다형성을 안전하게 쓸 수 있게 된 것이라고 한다. 다형성이 안전해진 덕분에 개발자는 본인의 시스템이 의존하고 있는 모든 구현체(implementation detail)를 교체 가능한 플러그인으로 만들어 버릴 수 있다. 시스템 사이, 모듈 사이의 결합을 느슨하게 만들 수 있게 됐다. 엉클밥은 더 나아가, 이렇게 할 방법이 있다는걸 알면서 시스템을 이런식으로 디자인하지 않을 이유가 대체 무엇이겠냐
고 반문한다. (The Future of Programming Languages 강연 중)
Tags: loose coupling, interface, dependency injection
Loose Coupling of a Mobile App
Programming is the task of efficiently creating software that works properly, and to do this well, you need to create code that is easy to maintain. A highly effective method to create a code that’s easy to maintain is to loosely couple an object. The Gang of Four said the following in a design pattern.
Program to an interface, not an implementation.
We call a coupling relationship which is independent of the implementation and relies on the interface, loose coupling. Loosely coupled code is easy to scale and maintain. It can still be managed as the program grows bigger and more complex.
The software design principle and pattern which allow loosely coupled codes to be written are called dependency injections. It is an element that cannot be found in a tightly coupled code, so to understand why this additional element is needed, you need to understand the advantages of a loosely coupled code first.
1. Late Binding is possible.
The implementation can be replaced without recompiling the code. Although not a perfect example, looking from a mobile app perspective, it’s similar to the principle where users can experience new features even when the app is not newly deployed when the OS gets updated or the framework provided by Apple/Android gets updated.
However, mobile app developers cannot relate to this. Because the app runs only in an environment defined and implemented by the developer, virtually there’s no need for the implementation to be replaced. For example, when creating an app that needs a database, there’s no need for a developer to make an assumption or even consider a case where his or her app is going to run on an environment with a different database other than the one introduced by that developer. Therefore, a late connection cannot be considered an advantage taken by a mobile developer. But there are more advantages of loose coupling other than this.
2. Easy to scale and reuse.
An app changes its requirements according to the users and continues to evolve according to the business. If the class/module is loosely coupled, it becomes easier to develop a new feature or modify and expand existing ones. Loosely coupled codes are open to scaling and closed to modifications. In a loosely coupled code, there is a separate composition root, where objects are assembled. Since actual implementations are created and injected here, it is not necessary for the codes that are using the interface to change.
For example, when there is a payment feature in the app, if the code on the product side relies on the payment-related interface, you don’t have to touch the codes from the product side that use the payment features when improving or restructuring the payment flow. You can think of A/B testing in a more general way. When you need to provide the same feature in several ways, you may add or remove a new feature without modifying the code which calls the feature.
3. Parallel development is possible.
As the project and the team grow bigger, many developers will work in parallel in one codebase. If the codes are loosely coupled, it’s easier for the developers to work on several modules simultaneously.
Grab mobile development team has more than 100 developers divided into less than 10 big TFs(Tech Family) in mobility, food, payment CX, etc. Each team uses features developed by other teams(real-time chat, payment, balance inquiry, reward points, user information/authentication, etc.) and is able to simultaneously develop the super-app thanks to loosely coupled codes.
4. Maintenance is easy.
A code that clearly distinguishes the boundaries and roles of classes and modules is easy to maintain. When developing a new feature, it’s easy to figure out where to modify it and recognize the scope of impact. Debugging is also less difficult in code that is coupled with a class or a module which has only one role. This is because if the role and the scope are well-separated, it’s possible to narrow down the point that may have caused the bug relatively well.
5. Testing is easy.
To be exact, unit testing is easy. To do a unit test, the test target needs to be isolated from its dependency. If the objects are loosely coupled, it’s easy to replace them as test targets.
There will be some people who do not appreciate the need for unit testing or the ease of testing for code structures. According to the Jetbrains developer survey of 2021, 62% of Swift/Obj-C developers do not make unit tests. However, once you experience the benefits of automated testing (with a little exaggeration), you can’t go back to the days when you didn’t make test codes.
Unit testing allows for the automation of significant testing tasks. More than 100 developers are creating hundreds of thousands of app codes in a month, it’s practically impossible to manually check the actions of the new and existing codes without unit testing. When our team was just newly created in Grab, the code coverage was low, but after more than a year of adding tests, the number of regression bugs and critical bugs decreased noticeably as a result.
Conclusion
According to Uncle Bob, the most powerful weapon given to developers by object-oriented languages is the safe use of polymorphism. Thanks to polymorphism being safe, developers can make all of the implementation details that their system is depending on into replaceable plugins.
It became possible to make the coupling between modules loose. Furthermore, Uncle Bob questions what is the reason for not designing the system this way when you know you can do it this way. (From The Future of Programming Languages Lecture)
Tags: loose coupling, interface, dependency injection