Author: Rıdvan KÜÇÜK, SW Engineer – iOS Development – UX & Mobile Applications Group
Choosing the right architecture that fits your needs is so crucial. There are several architectures available on the iOS development. Some patterns are based on Model-View (MVX) and another pattern which is separated from the MVX based one is VIPER. VIPER is acronym to View, Interactor, Presenter, Entity, and Routing. In this post, I am going to compare the most popular ones; MVC and MVVM. Basically, popular architectures by the iOS community are;
- MVC (Model-View-Controller)
- MVVM (Model-View-ViewModel)
- MVP (Model-View-Presenter)
- VIPER (View-Interactor-Presenter-Entity-Routing)
Model is responsible for encapsulating the data. View is responsible to present User Interface (UI). ViewModel / Presenter / Controller is kind of a bridge between view and model. The main responsibility is to update the model based on the user interactions and show.
If you made some research about details of the architectures, you should be asking yourself some questions. Did you? If the answer is yes, you are on the right way. Possible questions in your mind might be as follows:
- Why is my View Controller too crowded?
- How can I write tests for Massive (Model) View Controllers?
Apple’s expectation with the MVC pattern is to separate controllers, views and models from each other and communicate in an organized way.
However, the reality differs from the expectations. In Apple’s MVC pattern Controller and View classes are united. View Controllers are involved to View’s life cycle. You may think everything is perfect until unit tests. While writing the unit tests you will recognize that they are coupled.
The consequence of the MVC:
- Not able to write tests well.
- Easy to write code. Unexperienced developers can understand and update the code easily.
- View and View Controller are coupled. The balance is not handled very well.
For the MVVM pattern, developers are familiar with Models and Views. However, View-Model is a new thing. It is a bridge between Model and View. Model is connected to the View-Model and View Model binds to View. So, View-Model updates the model and binds to the View Model with the updated model.
Tip: Do not import UIKit in the View Model…
View Model knows nothing about the View. View-Model emits the changes and View observes that changes. So you can write unit tests easier than you do with MVC because it is separated! Another advantage of separating the concerns is that you have balanced code, not a crowded View Controller.
The consequences of the MVC:
- Ability to write unit tests for Model and View-Models which are separated from the UI dependent parts.
- Not easy as MVC. But when you have gained experience with bindings, it will be easier. It is hard to break the architecture by unexperienced developers.
- View, View Model and Model are separated from each other. View Controller have less code now!