poniedziałek, 26 stycznia 2015

Why you should use MVVM instead of MVC

The View-Controller in MVC is responsible of interpreting the Model (business logic) and managing UI. See that "and" in the middle ? It's a sign that a class might be breaking the Single Responsibility Principle

In theory, MVC sounds pretty nice, in practice it usually ends up the same: view controllers end up bloated and huge. They mix a lot of logic inside, which makes them hard to reuse and to test.

Microsoft to the rescue!

I have experience with Windows Presentation Foundation and I've learned a one very useful pattern there: MVVM. MVVM is almost like MVC, with slight different distribution of tasks. 

                                                           source

ViewController is now a part of the view. It's responsible for the UI: animations, dynamic changes, adding views, removing views, etc.

ViewModel is something that can be used in different projects, not only iOS. It's your business logic.

It takes data from the model, and interprets it. 

This way you achieve decoupling and you can test your business logic very easily. Something that was very challenging with ViewController.

Data Binding

MVVM is very powerful when combined with data binding. You can set your View to react to changes in the ViewModel via callbacks/events. This way you don't have to think what to do when certain data changes in the ViewModel, it's done "automatically".


Reactive Cocoa

How would we implement data binding on iOS ? Probably through some event system or Key-Value Observation (KVO). There's a cleaner way: functional reactive programming. We can achieve the functional programming in Objective-C thanks to a framework called ReactiveCocoa. Reactive Cocoa is built upon KVO and it saves you a lot of time, also making your code cleaner. MVVM and ReactiveCocoa is a great match for creating independent, clean and reusable modules of a system. Here's a great tutorial to get you started.