Refactoring Massive ViewControllers with Services.
Having all the logic inside of ViewController is a terrible idea and you know it. And when you open another MainViewController that contains 3K lines of code you feel that something has to be done about it. But where to start? Your inner perfectionist whispering to move all this code into the trash and rewrite it from the ground. It is extremely hard to refactor huge amount code in one sitting. So most of the time this code remains untouched and called “legacy” if not worse.
If you’ll look at a common iOS app (or a mobile app in general) from a greater perspective you’ll see that it actually doing one thing: gets data from the server, modifies it and presents it on the screen. Server side is not your realm, so leave it to backend guys. There is probably an infinite number of improvements that you can do with User Interface. Since it is the thing that constantly changes you may improve its flexibility (Check my article on styles), performance and reusability.
But server communication logic remains almost untouched from version to version. So, just by pulling that logic out from ViewController you can dramatically improve the overall quality of your code.
And this is where services come in handy. They are easy to implement, don’t require to refactor a ton of stuff and you will immediately see the difference.
So, what is a service? A service is an object that encapsulates the logic that related to one task or group of similar tasks.
Let’s say you have a UserViewController that shows information about a particular user in your app. It may look something like this:
There are many problems with code like that. Author was so lazy that he or she put all this code inside a viewDidLoad() function. Clearly, the very first step that you can make is to move that into another function. But what if we took this a step further and move this code inside another object?
By the magic of ⌘C ⌘V we can achieve this in a matter of seconds:
Not a big deal, huh? But it makes our code so much better in every way. Look at our UserViewController:
By doing this simple trick we can actually reuse code, test it independently and encapsulate other logic inside of it. After adding all user related logic into UserService class it will look similar to this:
Services could work with local data storage (CoreData, Realm etc.) or fetch data from the server. The main advantage here is the separation of responsibilities, reusability, incapsulation, testability and it all achieved without a lot of work.
If you enjoyed this article, please, take a second to recommend and share it. Thank you!