Refactoring storyboard related code

I’ve always had some kind of love/hate relationship with Storyboards. Probably like everybody. I found them frustrating and usually ended up with “fuck it, let’s loadView: everything instead”. The issue with this kind of approach is no matter how good you are, no matter how clean is your code, it’s hard to imagine the look of your view just by reading some code.

With a little bit of practice, a new release of Xcode and clever tools such as StoryboardLint I’ve found Storyboards to be a lot less of a pain than it used to be.

Still, there is one thing that I don’t like with storyboards : the huge prepareForSeque:sender: method. It’s basically he AppDelegate of ViewControllers and usually ends up containg a lot of code. Until today mine was 100+ LOC long and I figured it would be smart to clean this mess before the application goes live.

For obvious reasons I cannot share the actual code but it was something like this :

I often needed to inject the same objects, for exemple a managed object context for my Core Data stuff or a user instance shared across my view controllers. I know I should just have used a singleton and be done with it but a) I’m not a big fan of singletons and b) I just gave a presentation about unit testing where I suggested to avoid them.

Protocols to the rescue!

As most of my objects needed the famous PCSUser instance, I ended up with what I find to be a pretty elegant solution. I created a protocol, in this particular case, a PCSUserAwareProtocol :

Then, when a view controller conforms to this PCSUserAwareProcol, I simply inject my user using the mandatory setUser: method. Note that if, like me, you’re already using a @property, there is no extra work required.

I’ve adopted this approach for all the objects that needed to be injected in a couple of view controllers. I saved a few line of codes and made my method a lot clearer.

It’s still a bit fresh in my mind and git knows how many times I’ve tested new approaches on this projet. I’m @palleas on twitter, feel free to ping me if you’ve a better approach in mind!