CodingAdventures, Swift

TIL: protocols and lazy var

TIL this builds:

Swift never ceases to amaze me

CodingAdventures, Swift

TIL: Swift 4 and protocol composition.

One of the things I like most about Swift is that almost every day I learn something new, more often than not, something new that makes me write more readable and cleaner code.

Today I realised that protocol composition, which I kind of knew could be used to compose a SuperClass and a Protocol, can help remove some downcasts at runtime, and substitute those downcasts by the compiler yelling at you when writing the code.

Let’s take this code. As usual, it is difficult for me to come up with a relevant example that illustrates what I want, but is also simple enough to be understood without too much context.

Notice how I have to check, at runtime, that the parameter I pass to deliverPresentation implements the Presentable protocol.

If we rewrite the Presenter to be like this, we can make the compiler enforce that whatever we pass to deliverPresentation as a parameter also implements Presentable, so we can avoid the downcast.

A real life example? From this:

To this:


CodingAdventures, Swift

Building boundaries with third party libraries

The joys of jet lag. Here I am, at 2:43 am, trying to finalize a post that I started writing a couple days ago, while flying over the Pacific Ocean.

This is about dependencies, those third party libraries that often provide out of the box solutions to complex problems we need to solve.

Importing a third party library will save time and effort. Just add a line to a pod or Carthage file, and boom! We have saved days, weeks or months of development.

There are multiple benefits in relying on a third party library. Popular libraries are often well tested, and contain the knowledge of many developers about a given problem. Third party libraries save development time. Third party libraries avoid reinventing the wheel.

But third party libraries are code that you have not written, code that you don’t actually own, but that you somehow have to start maintaining as soon as you import it into your codebase.

Let’s take an example. Loading images, asynchronously, without blocking the main thread, in a table or collection view cell is a complex problem. We need to cancel image downloads when cells are not visible anymore, we might need to handle cell reusability, and ideally we should cache images. None of those problems are trivial to solve, and might require time and finesse to get right.

On he other hand, we could just import a third party library, like, for example, Kingfisher.

All we’d need to do would be adding a line to a pod / carthage file.


We have created a subtle problem here: our cell’s code depends on Kingfisher. We need to call a specific method in that library, passing a set of specific parameters, in the way that library expects.

That be not be a problem if we only have one cell. But things start getting dangerous as soon as we have more than one cell.

Let’s say there are 10 different cells that present images in our codebase. Kingfisher is so convenient that we will repeat the same code in the 10 of them.

What would happen if, for some reason, Kingfisher stops being maintained? Or a new version of Swift breaks source compatibility again, and this library does no get updated? Or a new library comes by, that is twice as efficient as Kingfisher.

Then we would have a bit of a problem. Our code is strongly coupled with the specific api of a very specific library, and updating our code to use a different library might require getting into shotgun surgery mode.

Shotgun surgery.

How do we switch? Well, we could just do a search and replace, or search all the calls to Kingfisher and update them to use the new, hottest library.

But that is not very efficient, obviously.

So how do we avoid the problem?

Building boundaries

The same way that we have tools and mechanism to decouple some parts of our code from some other parts of our code, we have tools and mechanisms to decouple or code from third party libraries.

And the best tool for decoupling things is, as usual, a layer of indirection.

In this case, we could add a layer of indirection by encapsulating the call to the third party library in an extension to UIImageView. This extension would be code under our control, and will contain a single point of dependency with the third party library.

Our cells will load images by calling a method that belongs in our side of the codebase, not in the library’s side of it.

Now if we want, for whatever reason, to switch to a third party library, all we have to do is modify the implementation of our extension. Import a different library, update the presentImage method to that third party library’s API, and we are good to go.

Final words

Introducing seams between our code and third party libraries decouples our code from external dependencies. That way, we are free to modify those dependencies without having a big impact in our codebase.


Kingfisher is a great library that solves a complex problem in an elegant way. I strongly recommend considering it.

CodingAdventures, Java, Swift

Things I like about Java: Anonymous classes

Everybody that knows me in real life knows that my favourite jokes are always those about Java being slow and bloated. But still, in all fairness, Java has some good things.

One of them, rendered obsolete by Java 8’s Lambda Expressions, that I always liked and that I really wish was possible in Swift, is Anonymous classes.

The way I see it, an anonymous class is just a syntax shortcut to declare and instantiate, inline, an instance of a specific interface. It is a quick way to create lightweight objects at the moment they are going to be used, or passed to another object.

Anonymous classes have access to the members of its enclosing class, and local variables in its enclosing class marked as final, which makes them great candidates to be used, in particular, to declare callbacks in particular.

To me, their greatest advantage is that anonymous classes allow you to encapsulate behaviour in a way that you only declare implicit types when you expect to actually reuse them.

Still, Lambda Expressions, similar if not equal to what in Swift we know as closures, might make code more concise in some situations. So, as usual, it comes down to knowing your tools, and careful considering which tool is the best for the job.

Updated on Sept 24th.

Joe Fabisevich points out that something similar to what the sample code does could be achieved in Swift by typealias-ing a closure, and typing AThing’s doAThing parameter as said typealias.

Which is quite similar to a solution based on Java lambdas.

If we need to declare more than one method in the Command interface, though, this approach would fall sort.

Joe also suggests another option in Swift:

This still requires making a type, but it is (or can be) private to the Main class, which in a way achieves the same goal as an anonymous class. It would be a concrete type, yes, but known only to the type enclosing it.


CodingAdventures, Java, Swift

Elegant Swift: Default Parameters vs The Builder Pattern

I was re-reading Effective Java (it is a rainy Sunday afternoon in Vancouver, and if you are stuck at home, and you happen to be European, and therefore you don’t really care about what Americans call “football”, re-reading Effective Java is not as bad as it sounds) when I soon stumbled upon an example that I think highlights the elegance of Swift (and, to be completely fair, also Kotlin’s).

Effective Java’s Item #2 says: Consider a builder when faced with many constructor parameters. Which makes total sense, if you ask me.

I am not going to discuss or justify the Builder Pattern now, but let’s just assume that it is more than justified.

The canonical implementation of the pattern, and I am going to take the liberty of using the code sample used in Effective Java without any modification, would read like the following (servings and servingSize are the only mandatory parameters, the rest are all optional)

If we follow the pattern to the letter, it translates into Swift like this:

Which is a lot of boilerplate, no matter how you look at it.

We have discussed Swift’s Default Parameters before in this blog, but in the context of Dependency Injection, in particular when focusing on testability.

But the thing is that Default Parameters, like many other Swift artifacts (or constructs, or whatever is the right word to refer to “stuff that Swift provides and makes your life easier”) can make code much more concise, readable and easier to understand and reason about while removing some of the bloating that certain languages (I’m looking at you, Java) are known for.

Because when providing default values to all the optional parameters, this is how our NutritionFacts look.

Much better, eh?

CodingAdventures, Swift

TIL: A pleasant surprise when passing closures as parameters

This one might be obvious, but it was a very pleasant surprise.

Let’s say we have something like this:

And a regular function like:

Then, Xcode will provide this code hint:

And now I can do:

Which I guess is not that unexpected. But still, a pleasant surprise.

CodingAdventures, iOS, Objective-C, OOD, Swift

Protocols as boundaries between the known and the unknown

In the previous post, we discussed how protocols 1 are the foundation of polymorphism, and how using protocols we can define a contract, an expectation, that can be implemented in many different ways.

Today we are also to explore how we can use protocols as a way to use code that does not exist yet, as a boundary between what we know (our code) and what we don’t know (other people’s code).

In an ideal world (maybe not ideal for everyone, but that would be a different discussion) we don’t develop our software in isolation. We have team mates, or we use modules or frameworks developed by other teams within the same company.

Some time ago, I was with a time developing a set of Video On Demand applications. We had to implement a new feature: add support for recommendations based on user’s content consumption habits. The recommendations engine was not developed yet, in fact there was no team assigned to build it at that time.

We knew were our side of the solution started and ended. We knew we were going to need to tell the recommendations engine that a user had watched a particular item, and we were going to need to get a list of recommended items from the engine.

We started by defining our own interface for that recommendations engine. We looked at the problem from ur side of it, and wrote the interface we wished the recommendations engine had.

Did we know how the actual interface of the actual recommendations engine would look? Not at all. Did we care? We did not.

But we could start working on our side of the solution using fake data.

Having a clear boundary, clear separation between our side and their side, allowed us to build our side completely decoupled from the recommendations engine.

Having a clear boundary also gave us the confidence that we would be able to adapt to whatever the actual interface of the recommendations engine would look. And why I mean by adapt is literally write an adapter between our interface and the actually interface of the engine, if necessary (see the Adapter Pattern)

Also, having a clear boundary allowed us to unit test our solution from day one, giving us the confidence we needed to move forward fast.

It’s not rocket science. But it is worth remembering that protocols are not just those things that you use for table views data sources and delegates, but that they are probably the most powerful tool in our reach.

  1. I have never been a fan of how the Cocoa frameworks use the word protocol instead of interface. ↩︎
CodingAdventures, OOD, Swift

Fun with protocols

Back in the old days, people used to communicate with each other by shouting.

But soon, people found that shouting was not practical. The receiver of a message could just be too far away, or sleeping, so humanity invented written messages. And so snail mail was born.

Fast forward a few hundred years, to the early ages of the internet. Someone, somewhere, invented email, so now people could communicate like this.

Soon, people realized that even though email was great, there were other forms of communication. What’s even more remarkable, people were happy sending emails, but they soon realized that what they really wanted was to be able to do something slightly different. Instead of sending emails, they just wanted to send messages.

Some of those messages would be emails, some of them would be snail mail, some others might even be some unknown technological marvel soon to be discovered. But what all people knew is that they did not wan to be constrained by being able to send emails and only emails.

And here is when people realized that the way they had been approaching communications was slightly unadaptable.

One of the few software engineers on the face on earth at that time, decided to do something about it. She started thinking about what people wanted, and why they could not have it, and soon realized that the actual problem was that there was a hardcoded dependency between a Person, and the way that person was able to communicate.

Our hero also realized that the reason why that was a problem was that what people really wanted was freedom of choice, and flexibility, and being able to send messages by multiple different mechanisms, not only email.

And that made her think: “maybe what people expect are not things, but behaviours”. Indeed, People seemed to have a clear expectation: “we should be able to send a message”, but different people wanted that expectation to be fulfilled differently.

Our hero thought “what people want to rely upon is an abstraction, not something specific.”1

So our hero started building her solution around an abstraction: a protocol defining a behaviour.

That allowed our hero to model a couple of specific implementations of that behaviour 2. For example, an email, an SMS, an iMessage (aka Apple Message, to avoid lowercasing a class, apparently all our hero firmly believes in coding standards)

So now, a Person could be taught to blindly rely on the abstraction our hero modelled, trusting it to know how to fulfill her expectations.3

That way, Cesar can send emails while Jodelle can send emails, or a hipster can send a Messenger Pigeon.

Our hero was satisfied with her implementation of the solution, specially because she realized that this design allowed her to provide as many means of sending messages as she wanted, without having to change the way a Person sends a message.4

Also, our hero soon realized that she could only test that messages are actually sent, by providing a very specific type of Sendable that did not actually send any message.5

And that’s the power of protocols. A protocol defines a contract, declares a behaviour, but does not define the way that contract of behaviour is implemented. A protocol is abstraction, and the details, the nitty gritty of how those contracts or behaviours are implemented are left to concrete implementations of the protocol.

Relying on abstractions instead of concretions, in general, makes designs more decoupled, open for extension and closed for modification, and highly testable.

CodingAdventures, Swift

Argument labels and parameter names

Today I learned that something that has been annoying me significantly when working in Swift, has a very simple solution, if only I knew my tools better.

This is a class. I have written a bunch of classes similar to this one:

That self in the constructor, annoys me to no end. I like how self is explicit in Swift, I think it makes the code more readable, less verbose, simpler. So, having it in the constructor, again, annoys me.

The solution is quite simple. Functions can have not only parameter names, but also argument labels.

Each function parameter has both an argument label and a parameter name. The argument label is used when calling the function; each argument is written in the function call with its argument label before it. The parameter name is used in the implementation of the function. By default, parameters use their parameter name as their argument label.

Adding an argument label:

And client code would remain unchanged:

I guess the lesson is, as always, know your tools.

CodingAdventures, Swift

Tableview datasources and the decorator pattern

Fair warning: Coming up with an example relevant enough to illustrate the topic, but simple enough to fit in about 1500 words is challenging. Take this code as a starting point, as a way to illustrate a discussion, and not as a drop-in solution ready to apply to a codebase.

Also, this solution can be applied to collection views. But again, for brevity, I will only discuss table views.

The previous post in this very blog was about going from the abstract and generic to the concrete and specific. It was, in a way, about specialising something abstract and generic, by subclassing it and providing a specific implementation for a specific type.

The sample code I used was more or less copied and pasted (with some info removed to protect the innocent) from the codebase I am currently maintaining. At the time I posted it it was holding well, but soon after that post I started having the feeling that there had to be a better way.

The problem

The problem I am trying to solve is a fairly common problem when it comes to iOS development: presenting lists of data without having an a lot of boilerplate code repeated again and again.

The usual way to present a list would be having a UIViewController that implements some or all of the methods in UITableViewDataSource.

That could be fine if there was only one data collection to render on screen, but usually, iOS apps are a sequence of screens that present data collections. Not only that, but usually, those screens are not that different from each other.

Sometimes, what changes from one data screen to another is the way a data item is rendered on screen (different UITableViewCells), some other times what changes from one screen to another is the presence or absence of section headers, or section footers, or both headers and footers.

So, if we approach the problem trying to abstract it as much as possible, what we would have would be a core behaviour (presenting data) that we might want to customise (i.e. adding headers or footers). And to make things more interesting, we want to do that in a way that reduces boilerplate and duplication and makes the solution testable.

The solution I have been exploring

The first step would be finding a way to factor out data management from view controllers. First, because it makes sense (a view controller should control a view, not manage a collection of data), and second, because by doing so we can remove a lot of boilerplate and duplication.

Shameless self promotion here: some time ago I published a framework to do precisely that.

There are other solutions, but I am sticking to mine for now, not because I think it’s better, but because, so far, it works for me. Basically, the implementation of the UITableViewDataSource protocol does not populate cells outlets, but provides cells with a model object, and trusts cells to know how to render that model object themselves. Tell, don’t ask!

So let’s start there. Let’s assume we are working on a task manager. We have a Task:

And we have a class to manage tasks as flat arrays. In real life, this data manager should be able to handle sections, but, again, for brevity, this one will be all flat:

Now, let’s move to the other end of the problem: the UI. As mentioned, cells will know what to do to render themselves when they are provided with data. We can model that assumption with a protocol that indicates that a cell will accept a model object, and a concrete implementation of that protocol:

A class implementing the required methods in UITableViewDataSource will look like this:

We provide it with a data manager, and a cell type. Notice how the implementation of the cellForRowAtIndexPath method only dequeues the cell, and passes it the model object that corresponds to its index.

So far, none of this solves the actual problem: customising data listings. But it send the foundation for a solution.

What was the problem again?

Let’s say that we have to render two different task lists, one of them without any section headers, and another one with a single section header. Let’s say also that we need a third listing with a section footer.

If we go all abstract, what we want is our datasource to behave slightly differently in different situations, while maintaining a core behaviour unchanged. Or, in other words, what we want is to add behaviour to an individual object without affecting the behaviour of other objects of the same class.

The Decorator Pattern

And that is, literally, the definition of the Decorator Pattern. So, let’s explore the Decorator Pattern a little bit more, and see if it can actually be a good solution to our problem.

(UML taken from wikipedia)

The pattern’s intent is clear: extending the behaviour of a certain object, independently of other instances of the same class. That will fit our case: we want some behaviour to remain unchanged but we also want to be able to customise some other behaviours, but only for specific cases.

There is another subtle detail here: the core behaviour, what we do not want to change, happens to be what is provided by the required methods in the UITableViewDataSource protocol, and what we want to customise, happens to be declared in optional methods.

That fits the pattern quite well. The ConcreteComponent could provide the behaviour we don’t want to change, provided by the require methods in the UITableViewDataSource protocol, and we could add ConcreteDecorators for each behaviour we wanted to add or customise.

So, just to recap, there seems to be a one to one relationship between the elements of the pattern and our use case: the Component would be the UITableViewDataSource protocol, the ConcreteComponent would be the Required class, and we can provide ConcreteDecorators that also implement the UITableViewDataSourceProtocol.

Let’s get to it!

This is the starting point:

We would also need an implementation of the UITableViewDataSource protocol that aggregates an instance of the UITableViewDataSource type, implements all the methods in the protocol and forwards them to the instance it aggregates:

And now we can start encapsulating the different behaviours we want to provide in subclasses of that TableDecorator. For example, if we need to provide a header title for a single section, a footer title for a single section, and header titles for multiple sections:

The beauty of this solution is that now we can add behaviours to the core behaviour of our datasource, in a composable way. Each behaviour would be well encapsulated, which in turn means that it can be easily tested, and it could also be reused eventually.

And what is even better is that we can mix and match behaviours without modifying the code in the core datasource, and without adding any conditional logic.

For example, if we want a table with section header and no footer, we can do this:

But if we want a table with header and section header and footer we can do this:

And if for some reason we wanted a table with a section header that is a slight modification of the previous one, we could just add another decorator like this:

That is the way we can compose optional behaviours: by adding them one by one, as layers of an onion, to a core behaviour.

Final words

I have ambivalent feelings about Design Patterns. I do agree that these patterns tend to be overused, and I have found myself a few times at that stage where all you can see are design patterns everywhere, and you try to solve any possible problem with an implementation of the Visitor Pattern.

But if design patterns are taken as what I believe they are, which is just one more tool, being able to identify them, and being able to consider the trade-offs of implementing or not implementing them can make a huge difference in the quality of a codebase.

In this particular example, having a collection of highly cohesive, loosely coupled and highly testable behaviours, that can be applied to modify a core behaviour at will, seems like a win.