Swift protocol extensions 102

Yesterday’s post was good. But what’s coming up now is even better.

The context

Imagine that, due to requirements, you need to have an insane amount of different classes (i.e views) that contain text labels. And you need to be able, due to requirements again, to customise some of those text labels. Not all of them, only some of them. And the funny thing is that you don’t even know which ones.

In other words, you need to provide a default behaviour that needs to be applied to an indeterminate amount of types, but that can be customised for some specific types.

Don’t you love being a software engineer?

The difficult solution

Sexy software engineers do not whine. Sexy software engineers roll their sleeves up, reach for the toolbox, consider all the tools available and implement the simplest thing that could possibly work. Or, like in this case, the simplest thing that could possibly work, while being scalable and maintainable enough.

And here is where protocol extensions com to the rescue again. This time, with a little twist: Generics.

First, we have our view. (for the shake of the example, let’s call it BaseClass)

Now, we have two different subclasses. Both do the same (again, for the shake of the example, in real life those two subclasses may or may not create the same amount of labels)

What is it that we want? We want a certain behaviour to be the default.

So, again for the shake of the example, let’s say we have a Label:

Here is the neat part. First we declare a Generic protocol:

We enforce Label to implement it, via an extension. Notice how we set the item type as the base class. Why the BaseClass? Because this would be the default behaviour applicable to all subclasses of BaseClass

Now, let’s assume that we want one of the methods in the protocol to have a specific implementation when the type passed to it is SubclassB. An specific extension will do it:

So, if we create an instance of SubclassA and another instance of SubclassB, the this would be the trace:

Final words

Protocol extensions are very powerful. We can use them to provide a default implementation of a protocol, and specialise that implementation for an specific type, either by applying the extension to types that comply to an specific condition (relying on the where clause) or by specifying the type of parameters that we want in the methods part of the protocol.

Swift protocol extensions 101

If you haven’t heard about Protocol Oriented Programming in Swift, you have been living under a rock for the last two months.

Protocol extensions in particular, which are at the core of whole concept, are neat and abstract and complex, and my brain hurts a little when I think about it. But the thing is, it is not that difficult to wrap your head around them.

Consider a protocol:

Now, we have two classes that implement that protocol:

But we want them to implement it with a little twist. We want ClassB’s implementation of method B to be a little bit different.

So we can start with a default implementation of the protocol, in a protocol extension:

And now an extension to that protocol that will only be aplicable to instances of ClassB

And if we do this:

We get this trace:

Boom.

Final words

Now, consider the second extension, the one I called ExtensionToClassB. What if, instead of applying that extension to a class type, I apply it to another protocol?

Mind blown.

rfFWukr

YADIW: properties

YADIW (you are doing it wrong) is a series of posts about some common code smells, and how to avoid them.

Properties are cool

Indeed.

That’s easy, that’s simple, so easy and simple, that it is easy to just write all your properties like that.

But

814993

Mutability vs immutability is always a hot issue. Are you having one of those endless boring days? Just raise this issue with another developer. You are welcome.

But, the thing is mutability is bad. Not only because mutability is by definition thread-unsafe, but because of the fact that mutable classes have, by definition, more than one state. And that’s bad because, when you are going to use one of those mutable objects, it just can be in the wrong state. Either you make sure that the state is correct (red flag, that means the abstraction is leaking) or just hope for the best and prepare for the worst.

In this case, when you need to read Identifier, you need to make sure that it has been set previously. Or prepare for obtaining a null value.

The solution

Make your class immutable. Like this:

Now, it is imposible to create instances of this class in any temporary state. And thread-safety.

Final words

Sometimes, a little bit of extra code, after some careful consideration of what the language provides, saves a lot of code and a lot of headaches in the long term.

About coding style guides

Tl;DR;

Coding style guides, like in “there should be one and only one whitespace before an opening bracket” are bad, and if you enforce them, you should feel bad. And kittens will die.

The longer version

Yesterday, when I was working on an Android codebase (yeah, I know, me doing Java, haha LOL), a build failed because I did not add a whitespace after a comma.

Well, that’s hardly worth a blog post, you might say. And you might be right. But the thing is, I think it is time to stop this craziness.

Style guides. Why?

Well, if you ask anyone that really believes in the benefits of enforcing a strict coding style, he would probably say standards are good because:

  1. A strict style makes code consistent. If different developers follow a common style, the code will always look the same, no matter who wrote it. Which leads to:
  2. A strict style guide enforces collective ownership of the code. You should not be able to tell who wrote a particular piece of code by just looking at it, by just checking the style. Which means, in a way, that if can not be attributes to a specific developer, if will be attributes to “the team”
  3. A strict style guide avoids meaningless diffs in pull requests. Like when, for example, someone adds an empty line before a return statement because of muscle memory.

Style guides. Really!?

Well, if you ask me, thought, my answer would be: I don’t want to work in a place that enforces following a 10 pages long style guide.

If a developer wants to write Egyptian brackets, while another developer needs to see the brackets in the next line… why should that be forbidden? What’s the benefit?

  1. Why is consistency so important? What makes code hard or easy to read is the intrinsic simplicity of it, not whitespacing. Unnecessary loops, poorly named variables, long methods with multiple responsibilities… those are some of the things that make code hard to read and understand. Not a whitespace after a comma.
  2. Even with a strict stye guide, you are going to be able to tell who wrote what parts of the code. If you know your team, and you don’t know to know your team that well for this, you will just know.
  3. Collective code ownership is not enforced by a style guide. Collective code ownership is an attitude, that people have or do not have. You, as a team lead, can do lots to build a team where everyone cares about the overall code quality, and everyone sees the final product as a collective effort, and no one tries to bale anyone else for bugs or defects or lower quality code. Creating that environment is your job, not a stye guide’s job.
  4. Yeah, inadvertent diffs. Mmmmmmmkay, I give you that one. I don’t think it really matters, but I give you that one. If avoiding those is so important to you and your team’s health, then automate the process. There are IDEs, plugins, scripts, all kinds of tools to enforce your beloved whitespacing. Just let those tools do their job.

I don’t think that word means what you think it means

This is what I hear when someone enumerates the benefits of strict style guides: “I want to micromanage every single aspect of your work”.

I don’t want to work for dictators. I don’t want to become one. Write your brackets wherever you want.

What’s new in Swift 2: throw

Error handling is hard. Error handling is tedious. And what happens when something is hard and tedious? It gets ignored.

How many times have you done something similar to this?

instead of this?

Riiiiiiight, you are the only one that never did that.

Error handling sucks

Let’s be honest. Error handling sucks, big time. Even thought the Cocoa frameworks (those on Mac OS X in particular) have always provided great resources for error handling and, in particular, error recovery.

But, you know, exhibit A.

So, here comes Swift 2 to the rescue, introducing something that will make roll the eyes to our Java-oriented friends in the house: throw

throw does not suck that bad

Yes, I know, I know, Java has been throwing exceptions for years, and Java this and Java that. But, first, Swift throws does not have any performance side effects, opposing to Java exceptions, (meaning, your program is not going to slow down to a crawl when you try to throw one) and second, and most important, using throw, and its sidekicks try and do catch, you can make your code intent extremely clear and obvious to anyone reading your code (including yourself in a couple of months time).

So, how does the awesome shinny new thing works? Actually, it is quite simple.

If you want to Do Things Properly(TM), the first thing you would need to do would be declaring your error type, which should conform to, surprise, ErrorType. Why would you ever want to conform to ErrorType? Well, because that’s what NSError conforms to. Wink, wink, nudge, nudge.

So, again, your error:

Remember the previous post? We had a function that bailed out as soon as a set of sanity preconditions where not met. Well, let’s rewrite that one to, instead of just bailing out, throwing one of your shinny new errors.

Please note that, in theory at least, throwing an error is not supposed to be that different from an early return. Specially in terms of performance. In other words, throwing errors is the cool thing to do now.

Now, clients of this function can do this:

Note how you must add the try keyword when calling a function that throws something. Explicit much?

Final words

Now, as usual, reader discretion is advised. Use this at your own risk. It is not that hard to end up with code like this:

What’s new in Swift 2: guard

I have been refraining from writing a “What’s new in Swift 2” post for too long. I need to do it, because I need to really wrap my mind around the new stuff, and there is no better way of doing that than writing about it, but on the other hand, there are plenty of “What’s new” post already.

So, I’ve decided that I’m going to do it, anyway, but one step at a time. And, today it is time for guard.

The problem guard solves.

Let’s assume that we have a function that needs to divide two numbers And for the shake of the example, we want those two numbers to be optionals.

This would be, more or less, the Objective-C way of doing it, just translating the code to Swift.

The good thing is we bounce out of the function immediately. The bad thing is well, overall ugliness and force-unwrapping, and kittens dying.

So, if we do it The Swift Way, we could something like this:

It gets better, but still, the function looks, at least to me, a little bit upside down. We don’t bounce out of it immediately, we first check the happy path, and go through it, if possible. And in doing so, readability drops.

We could refactor that function, to have only one return point. In a way, the code would look neater, but we are not bouncing early, which was kind of the point of the whole thing.

The way guard solves it.

So, here comes guard to the rescue. Basically, guard statements only run if the conditions are not met, which is precisely what we want here:

Final words.

I guess there is not much more to add at this point. guard makes the code neater and more legible.

In my book, that makes it a keeper.

Protocol Oriented Programming in Swift

Unless you have been hiding under a rock during the WWDC week, you have already heard the buzz surrounding the session named Protocol-Oriented Programming in Swift.

I have to admit that, for me, it was one of those moments when a lot of the things finally click together: some of the intuitions I’ve had in the last years, the certainty that there had to be a better way, but not knowing exactly how to find it, the feeling that the Java/.Net approach to OOP leaves much to be desired, and in particular, the conviction that often times we look at the wrong abstractions, and we must abstract behaviour, and not entities.

Obviously, a session like that would not have been possible a year ago. Some of the new features introduced with Swift 2, in particular protocol extensions, make that shift in paradigm possible.

And that, to me, is precisely what is important here. Apple continues to tell us developers to think out of the box, to Think Different (that very last slide in the presentation gave me the goosebumps). Yes, we are different, we have always been different.

We are creative, resolutive, reckless, relentless people, that love thinking out of the box, and find solutions to conventional problems in an unconventional way.

We are still expected to Think Different. And I love it.

TDD and Xcode 7

I was about start writing the mandatory “What’s new in Swift 2” post, when I decided that yet another post about try and proper Generic support in enumerations was not precisely what the world needed.

So, since TDD is so near and dear to my heart, here is an overview of what’s new on Xcode 7 (as of beta 1), when it comes to unit testing.

UI Testing, made easy!

Finally, there is a way to test user interfaces. Well, actually, there has been one for a long time (UIAutomation), so let me rephrase: finally, there is a simple and well integrated way to test user interfaces.

By this time, I guess everyone has seen a demo, or the relevant WWDC session recording, but it is as easy as clicking a button, start interaction with the UI, and then add an assertion.

By the way, no offence, but it is just the demo mindset, but Apple’s testing samples usually include more than one assertion by test. Not cool. Tests should fail for a single reason.

Anyway, the cool thing is not only how easy it is to test UIs, but that a UI testing target is added to new projects by default.

Test all the things! No not add all the things to the testing bundle!

There is no need to add production code to the testing bundle anymore. If you recall, until now, if you wanted to test a particular Swift class, you needed to add it to the unit tests bundle as well. Not cool.

Now, all you need to do is import the module under test using the @testable keyword. That is cool, because, again, you do not need to add your production source to the testing bundle, which is ugly and dirty, but is also a little bit meh, because if you import a module as @testable, you are able to test all the stuff marked as internal. Which in a way makes sense, because internal means, well, accesible to the module, so it is kind of expected that if you import the module for testing, you should be able to test it fully and properly, with tests that have the same access privileges as the rest of the module.

But, on the other hand, it smells a little. Maybe it is just the mantra “test only public behaviour”, which I am also guilty of repeating over and over again, voicing out its concerns.

TDD Support

I kind of recall reading somewhere or watching in one of the WWDC videos that there is some kind of improved support for TDD in Xcode 7.

All I can see is that, when showing the Assistant Editor, there is an option in the Navigation Bar, or Counterparts bar, or whatever that’s called, that provides a shortcut to the Tested class. But I couldn’t make it work, maybe just because I was trying to TDD the crap out of a struct and not a class (how to choose between those two is a matter of another lengthy post coming up soon).

On a side note

I love the new font in El Capitan. Source code looks very pretty on a retina display.

Oh, yeah, and TDD FTW!

Introducing Turnstile: Finite State Machines in Swift

I guess reaching a certain age makes you reflect on stuff like the meaning of life or the purpose of your work. Not much can be done about the first of those concerns, and if you want to make a somehow decent living, I am afraid you can not do too much about the second either.

However, if you are a Sexy Software Engineer, there is something you can do to fulfil your heart’s desire: open sourcing something.

It does not need to be your life’s work, it does not need to be something that will change the way software is developed, or end world hunger. A repo in github is more than enough.

Finite State Machines

At this point you are probably wondering if this is an actual post about actual software or not. Yes, it is. This is all about State Machines.

State is my favourite design pattern, by far. The first time I heard the words “design pattern” was when I was introduced to State. It was my first day in my first job as an “engineer” (which I later understood was a very different thing as being a “programmer”). To this day, I still remember how I felt when my team lead was explaining it to me: it was a mix of incredulity, fear of the unknown, and a more specific fear of being fired as soon as everyone noticed I was not understanding a single word the team lead was saying.

What problem do State Machines fix?

Indeed.

I guess the easiest way to describe it would be this:

The State Pattern allows objects to behave in different ways depending on their internal state

A simple example of an object that behaves in different ways depending on its internal state might be a play/pause button. If you press the button while it is in the “play” state, whatever is being reproduced will be paused. If you press again, playback will start again.

Now imagine the same button, with another two or three states. Then, the logic to handle the button will start getting more complicated. You might need a switch statement to handle it, you might even need to nest if clauses. In any case, your logic gets quite complicated, and therefore your code will get more error prone and difficult to maintain.

How do State Machines fix that problem?

Instead of having complex logic to handle the different states, declaring a State Machine is just declaring a set of States and the transitions between them.

Transitions are just links between an initial and a final state. Now, it is just a matter of figuring out a way to to trigger those transitions, in order to change the object behaviour.

Turnstile

Turnstile is a lightweight implementation of the State pattern in Swift.

Creating a State Machine can be achieved like this:

Then, it’s good to have some transitions between States. You know, in order to transit between events and stuff:

(Now it might be the perfect time to reflect on how awesome it is that Swift supports emoji)

Triggering transitions is as easy as:

Turnstile is distributed as a CocoaPod, and is available on github. It includes a sample project that illustrates the way to create and use Finite State Machines.

Bash tip: search history

I am lazy. And I am a developer. Some would even say that I am a developer because I am lazy.

Also, my memory is not what it used to be. So, often times, I can not remember the exact syntax of a command I kind of recall typing in the bash shell.

For example, I kind of recall that in order to build and deploy one particular app for QA, I need to run a gradle task with a parameter containing the letters “QA”. But I don’t recall the specific format.

Here comes history to the rescue. A fuzzy search on the history is easy:

Now, I can execute any of those particular results directly by number, just doing: