The Week in Cocoa News

Greetings, fellow Cocoa developers, and welcome to a new edition of The Week in Cocoa News, your weekly mash-up of bad jokes and links to blogposts and articles of interest to the discerning Cocoa developer in your life.

So, let’s get the bad joke out the way first. And trust me, this is a really bad one

Knock, knock.

Race condition.

Who’s there.

Badum-tsh!

Before you shoot yourself, read the following post. It contains plenty of what’s best about Swift -type-safety, the possibility of avoiding all “sting-typed” programming, easy ways to modify behaviour without relying on extension, to name a few-, in this case in the context of the “classic” Objective-C territory: UIKit

Let’s Get Meta: Swift Metatypes and Cell Reuse

Seriously, don’t do strings. Winners don’t do strings.

Anyway, here is a little bit more on types and meta types in Swift:

Types and meta types in swift

Enough with the meta-stuff! We started talking UIKit, so this looks like a good moment to link to this other post:

Unwind Segues as an Alternative to Delegation

Lately I have been reading a lot about DSLs. I believe DSLs are great tools that are greatly underused. Here is a good example of how a little DSL’ing can take you a long way.

Implementing a Small DSL in Swift

Now it’s time for another favourite of mine: unit testing:

Better Unit Testing with Swift

To be honest, most of the suggestions in that article are not about Unit Testing, but just about good engineering (injecting static dependencies, relying on abstractions -protocols- and not concretions -classes-), but again, this just prove the point of TDD: there is usually a correlation between good production and good testing code.

By the way, now that we are discussing testing. it might be a good moment to link to Nimble, the matcher framework for Swift (and Objective-C)

Nimble

And to wrap up this Edition of The Week in Cocoa News, deep linking and iOS 9:

How to Set Up Universal Links to Deep Link on Apple iOS 9

And that’s all, folks! See you next week, in another Edition of The Week in Cocoa News.

Private development, public release

This is one of those posts that people sometimes do in order to document something. In this case, this is me documenting something that I needed to do at work today.

What do we want? We want to publish something we have been working on to GitHub. But we want the GitHub history to be clean and tidy, while keeping the private history. We also want to be able to continue developing, as usual, with our private repo, but push new features from time to time to GitHub without exposing the whole private history. So this is what we did:

Intro

The following workflow seems to provide what is necessary to:

  • Develop in a private repo (stash/bitbucket) with the usual perks:
    • Feature branches
    • PR / Code reviews
  • Publish releases to a public repo in GitHub, with the following constraints:
    • Its own, clean public history.
    • History different from the private repo’s history, but not totally independent from it.
    • The release process to GitHub should be as simple as possible

The workflow

This workflow is based on the workflow described in this article: Our Git Workflow: Private Development, Public Releases

Add GitHub remote

This step can be done anytime before pushing to GitHub.

Initial commit to master

Right after the project is created from scratch, create an initial commit. This should happen immediately after opening a new project in Android Studio / Xcode / IntelliJ / AppCode…

This branch will be the private master, and can be pushed to bitbucket/stash

Create a release branch

Right after creating the initial commit, and pushing to master, create a release branch: release/release. This branch will contain the full history.

Create the branch that will be pushed to GitHub

Branch out from release/release, before adding any other commit:

At this point, there should be three branches, containing the same commit.

Work on a feature

Starting from master, checkout a new feature branch, and publish it to stash/bitbucket

After development is completed, and all work in this branch is pushed to the repo, the branch will be merged into master and removed from the remote. Make sure local master is up to date with the remote master.

Prepare a release

Local master is ready for release. So now it is time to checkout the release branch, merge master into it, and do whatever preparations are needed for the release (bump version numbers, update README or CHANGELOG files, and whatever else is necessary):

Now, the release branch can be merged into master. But the important step in the following:

Prepare the public branch

github-master is the branch where we don’t want to see every single commit in the private history. So, checkout the github-master branch, and merge the release branch into it, making sure it is merged as squashed. That squashes all the diff in one single commit, and leaves the changes stashed in the github-master branch, waiting to be committed in one single commit:

This will make the github-master branch history clean, with a single commit for each squashed merge.

Ta-daaaaaaaah

Generics, extensions, and where clauses: 😱

While trying to implement something completely different and unrelated to the code in this post, I found myself thinking really hard about the combination of Swift generics, protocols, and protocol extensions. But that is not the theme of this post.

But, usually one thing leads to another. At least, that’s what happens usually when I think hard about something: I end up figuring out something completely different. In this case, I’ve just noticed this:

From a purely grammatical point of view, the code makes perfect sense, but I am not sure if there is a real use case for it, at least a use case than can not be solved applying traditional polymorphism (i.e. using interfaces/protocols the way your favourite deity meant them to be used), but well, there it is.

And here is the playground, just in case: GenericsExtensions.playground

More about Enumerations and Associated Types

I have briefly covered Associated Types before, but I would like to discuss what I like about them a little bit further.

So, to recap, let’s assume we have an enumeration like this:

If we want to check what message is, we need to do this:

Now, imagine we only care about the case when message matches a tracking event (any tracking event). We would need to do something like this (which as I far as I know, was the only way):

Notice how (as of Xcode 7.1) we need to implement something in the default block. It can not be empty.

Now, somewhere along the journey, I honestly don’t recall if it was with Swift 2 or 2.1, this was introduced:

Syntactic sugar? Yes. Useful syntactic sugar? Hell, yes! It makes code more expressive and therefore easier to read.

And here is the playground: AssociatedTypes.playground

Making a protocol equatable

This morning I was playing with a couple of model objects, trying to find a way to make them conform to Equatable. That’s not a big deal, you might say… well, in this case I wanted to make the protocol those objects implement, not the actual objects, conform to Equatable, so things got a little tricky.

Let’s say this is where I started:

Now, I want everything that conforms to Drinkable to be Equatable. So this was my first attempt:

Nah-ha. “Extension of protocol ‘Drinkable’ cannot have an inheritance clause”

The solution? Turning things around little bit (would this qualify as “inverting the dependency”, haha-lol?) and enforce Equatable to respond to == when the type implementing Equatable is Drinkable. In other words…

Ta-dahhhhh!

Here is a playground, just for you: Protocol_Equatable.playground

Enumerations and mappings to other enumerations

Swift enumerations are cool, there is no doubt about it.

A lot has been written about enumerations, including some impressive articles, but the thing is, the more I use them, the more (neat) use cases I find for them.

What’s all the fuzz about enumerations?

Enumerations can implement instant methods and static methods, conform to protocols, declare variables, initialisers, and support extensions.

All of that, by itself, might not seem like it is too big of a deal, but when we put it all together, we can use all these great powers to achieve our ultimate goal as engineers: cleaner code.

Show me an example.

At the moment I am writing a thin layer (in Swift) built on top of a third party library (written in Objective-C). But the fact that the third party library is written in Objective-C is not that relevant to this example.

Let’s assume the third party library, provides a method with this signature:

Basically, what I need to do is track the progress of a video that is playing in a video player, according to something like this:

That, only because the developer that wrote the third party library was careful to declare his enumeration using NS_ENUM, so my Swift code can map to it without too much pain.

But, first of all, my code is ugly as a naked cat. And second of all, breaking down playback progress in quartiles is something that I will have to do in a few different places across my codebase, so it makes sense to encapsulate it. In particular, it makes sense to have an enumeration on my side of the line, that model quartiles properly. Something like this:

Cool, but not cool enough. If every time I need to track progress, I need to go through a switch like the one in the trackProgress method defined previously, I would’ the much better off.

So, what would I want to do, ideally? Well, all I need is a factory method, something I pass the current progress and the total duration, and returns the quartile we are in. Like this:

What’s cool about this? I wanted a factory, and since enumerations support static methods, I can have a factory. Neat!

Now, I want to map my enumeration (Quartile) to the enumeration that the third party library expects (TrackingEventType), which, if you have following the post, you already know was written in Objective-C

But, Swift enumerations support extensions, so..

Why an extension? Well, mapping Quartile to TrackingEventType does not look like it should belong to the Quartile Type. However, it makes more sense to me to separate it to an extension: if I need more mappings, I can add more extensions (Open Closed Principle FTW!)

The best part of it is how my trackProgressMethod looks now:

Which happens to be way cleaner.

Final words.

The usual: embracing Swift completely implies a slight shift in mindset. But that shift it is completely worth the effort.

Enumerations and associated types

This one is a neat little thing, but I think it totally deserves a post.

Swift enumerations support Associated Types, which are basically values of any given type, that can be stored in a specific enumeration case.

Here is an example:

The use case? In this case, providing two levels of hierarchical abstraction, with just one type.

The more I use Swift, and the more I’m letting go of the old patterns, the more I enjoy it.

Playground

Primitive obsession

If you have been following this blog (hi, mom!) you might have noticed a recurrent obsession of mine: stop looking at the wrong abstraction.

There is one case when looking at the wrong abstraction can be particularly dangerous: dealing with primitives.

Primitive what!?

Martin Fowler (bow) already explained this, better that me obviously, in Refactoring. “Replace Data Value with Object”, Mr Fowler wrote. “Apply this refactoring when you have a data item that needs additional data or behaviour”.

But what does than mean? Let’s see it with an example.

Often times, primitives (strings and numbers in particular) have special meaning. Phone numbers, addresses, email addresses, usernames… all of those are either numbers of strings, but those are numbers or strings with some associated “behaviour”, specially in terms of how they are represented or validated.

For example, consider a class that models a User. The proper way of modelling an User using a POJO would be something like this:

That class would pass 99% of code reviews without a single comment. It is immutable, it encapsulates the user data properly, and it does not expose anything it should not expose.

Now, let’s say we create a User like this:

And now, let’s say we create it like this.

Boom. Name and surname are swapped, and the user has an invalid email address.

Promoting primitives to objects

I have already discussed a similar approach to the one I am going to suggest now. However, there are some subtle differences.

Let’s discuss first the email address. An email address can be represented as a string, but there is some behaviour associated to it, because not all strings are valid email addresses. Email addresses need to be validated!

So, representing an email address as a string means that it will need to be validated every time it is going to be used.

However, if we have an EmailAddress class, we can either guarantee that instances of that class will only be created when they are provided a valid email address (as a string) or declare a method that validates the address.

If we did that, the previous constructor could be rewritten as:

Now, what about the name and surname? Well, we might want to add some behaviour to them as well, but I think the most compelling reason to promote them to objects would be type safety. Check this out:

Now, it is impossible to mess up the order of the arguments. The compiler will complain loudly as soon as you do not pass the right thing at the right place.

Isn’t that unnecessary complexity?

I wouldn’t say so. I would say that it is proper object orientation. A first name is not a string, although it is usually represented as a string, the same way an email address is not a string, but something with semantic value that, yes, can be represented as a string.

Now, obviously, this means more classes and most likely more objects living within the application cycle. True.

But software engineering is all about considering and balancing the trade-offs. And in this case, an extra class is a price I’m willing to pay in exchange for safer, more robust, and more cohesive code.

About enumerations in Swift

The last project I have been working on is a set of highly customisable applications, that need to render their user interface according to some configuration downloaded from a remote service. Meh.

But, the thing is, a setup like this leaves a lot of opportunities for Swift to shine. One of those opportunities is implementing color schemes.

The context

All the colours used in an application need to be declared as part of a color scheme, that needs to be downloaded from a remote service. For the shake of this example, we are going to leave the “download it from a remote service” part out of the equation.

A good approach

Well, this is Cocoa, so, the first approach that comes to mind would be declaring an extension on UIColor, and declare the different palette items in it. Something like this:

Which is a perfectly valid approach. But, that is basically a literal translation of what I would do in Objective-C, if I had to figure out a way out of this problem. Which is not bad.

But…

A better approach

The previous approach does not feel very Swift-ish. And, what is worst to me, it does not seem extremely flexible. For example, how would I deal with a requirement such as “yo, bro! can we make the color scheme change at runtime?. Like, you know, light theme during day hours, dark theme during night hours? That’d be sooooo coooooooooool”

Well, let’s try a fresh approach to the problem at hand. What’s a color scheme? To me, it is a set of mutually exclusive values. The active color scheme can be Light, or Dark, not Light and Dark at the same time.

And that, in Swift, is an enumeration. Also, it happens that Swift enumeration can implement methods. So, we could rewrite the previous extension as:

Now, we can set the active scheme as:

And consume it, everywhere in the UI as:

All of that, backed up by the compiler, which will make sure that we do not miss any possible value of the color scheme in its methods.

Final words

Switching to Swift is not only a matter of writing code in a different language, it is also a matter of forgetting about most of the old patterns, and embrace new ways.

And that sounds like a lot of fun to me.

Here is the playground: ColorPalette.playground

Sunsetting id

I am the first to be surprised to find a post about good old Objective-C in this blog. This Sexy Software Engineer has not written any Objective-C code in almost a year! This Sexy Software Engineer, though, still enjoys using the Royal We. Some things ain’t changin’

A little bit of ancient history

Those, like me, old enough to be around in the “good old days”, before ARC, when memory had to be manually managed, will remember how a proper constructor (sorry, initializer) in a proper Objective-C class was supposed to return id

id meant “Yo! Compiler! This is untyped! Have fun with it!” Or something similar. You get the point.

But then ARC came in with all its modern memory management, and all its fancy annotations, and suddenly, the right thing to do was to type return types in initialisers as instancetype

A little bit of contemporary history

Here we are now, one year into the Swift age. Lots of things have changed, and most of us do not consider the fully dynamic nature of Objective-C a selling point anymore. We might still miss it sometimes, but we like the warm and fuzzy feeling of relying on the compiler, and let it catch potential problems for us.

But, and this is a big but, we still need to rely on Objective-C libraries and frameworks daily. And those are not trivial libraries, those are the actual SDK frameworks (AppKit, UIKit and Foundation), which are still Objective-C

Apple is doing a great job in making the interoperability as smooth as possible. Please, watch the WWDC Session Swift and Objective-C interoperability right now, and you will get a great walkthrough everything that has been done in order to turn Swift code that uses Objective-C code into something safe. Let’s just say that now you can do something like this:

Back to the point: what’s with id?

By adding some extra metadata to the Objective-C code, like nullability and “kindof” annotations, or by embracing generics, Objective-C code will be more robust, less error prone, and Swift code that uses Objective-C can be safer.

Values marked as Nullable in Objective-C will be considered as Optionals in Swift. Typed Objective-C arrays will not be AnyObject arrays in Swift anymore. And that’s very good.

But still, what happens to id? Well, there are still two use cases for it:

  • Store different types of values in a Dictionary.
  • Type something as “any object implementing a protocol”

The second use case is something I have not done in many years (I always used to type pointers to protocols as NSObject <MyProtocol>).

The first one, is something that, although powerful, I always considered as a code smell.

So there you are, that’s the reason behind the post title.