Extensions are you best friend

I’ve been a fan of Robert C. Martins (Uncle Bob) book Clean Code since I read a few years ago. If I had to name one book that every programmer should bring to that fictional lonely island, then it would be Clean Code.

When learning a new programming language, you try to apply your old rules and improve upon thoose rules. Atleast I tried to do that. So after reading the Swift book and of course many blogs about swift I started to think about my models.

Let’s start with a simple example.

Person Version 1.0

A model representing a Person with two properties. First and last name. But what if you need to print the full name? Thats easy, I just add a simple function to my model.

Person Version 2.0

We are directly seeing some distorsion in our code. It’s not that clean and easy to read any more. And while readability is getting worse, you also added logic in to your model, which is a big no no.

So what would be a better solution? Some would probably add a logic in a new class, maybe a class that takes a Person and returns a “full name”, others would probably add the logic in a controller. Adding new classes for every little logic for a class can be cumbersome and also bloat your project. Putting the logic in the Controller (M-V-C) is a better solution, but why not just an extension? Controllers are hard to to reuse, and we should follow the DRY (Don’t Repeat Yourself) principle, right?

Person Version 3.0 — Extensions

We separated the logic into the extension. The implementation of this logic is close to its model and can be reused everywhere in your module.

Protocol conformance through Extensions

I recently discovered (yup, never thought about it before swift) that you can add protocol conformance with class extensions. So in this last example I added a AgeClassificationProtocol and required Person to implement age and return agetype. Age is a read only property sat in the initializer, this should probably be changeable in the a real world example.

Person Version 4.0 Put your protocol conformance in Extension

Look how clean our model Person still looks, there is almost no noise at all. We implemented some basic logic (some purists may find this way disturbing) and protocol conformance.

There you have it. This is an approach I use and like. Some might not like it some will. This doesn’t only apply to your models, but all your classes.