A little of refactoring goes a long way

Or yet another slightly misleading title for a blog post.


In my product, I want to be able to propagate errors to the UI. Any kind of errors. Network errors, and all things related to network errors are a fascinating example.

Let’s say that I want to display a message every time a network request fails, or has an unexpected result (no data, unexpected response format, parsing errors, whatnot)

On way of doing that might be:

Please note how DisplayableMessage, of course, extends ErrorType. Because being a good citizen in your platform matters.

I don’t want to bore the user to death with the details of what went wrong, so I just want to do this every time there is networking error:

The little refactoring mentioned in the title

What’s the issue with the previous approach? Well, If I want to create instances of Message to model all network errors, I can assume I am going to have create said Messages in different points within my codebase (i.e. the parsing layer and the networking layer)

What should a sexy software engineer do? Embrace the Factory Method. How? Like this:


Why does that refactoring go a long way?

Now we have a method with a name that clarifies the intent. I want a networking error, so I call the method that provides one of those. That way, clients of Message do not need to know anything about how that error is constructed (which parameters do I need to pass, in what order?)

Also, like any other creational pattern, this factory provides a layer of indirection when it comes to create the actual objects that we want to consume. Do I need my instance of Message to be unique? Easy, that’s an isolated change. Do I need to change the error message? Easy as well, that’s another isolated change.

Final words

Now, I guess you get the post title: a little of refactoring can go a long way. Sometimes.

No-one actually knows what they are doing

Earlier this morning, I found myself trying to help a colleague remove some duplicated code.

There it was. The big acronym: DRY. Don’t Repeat Yourself. The mantra that every aspiring Software Craftsman repeats ad nauseam.

Duplicated code has somehow become, by far, the biggest possible issue in any code base for some kind of developers (not the colleague in this example). And that, to me, is an issue.

What did you say? Did you say DRY is bad?

I did not say that yet. But I will say it now: DRY is bad when it leads to adopting poor solutions to problems, when it leads to bad architected solutions.

A certain degree of duplication is not bad. It actually helps discover abstractions, it helps simplify the design, or at least it helps discover where it is actually necessary to have a point of extension. And this is not the first time I write about this.

In particular, a certain degree of duplication might help you avoid this:


Because, yes, excessive inheritance, or relying on inheritance to solve every single problem is bad. Very bad.

There is nothing like a “one true set of best practices”. There is always more than one solution to a single problem. To the question “what is the best way to do X?” the answer should always be “it depends”.

We have a set of tools to reach for (extension, composition, design patterns, abstraction, interfaces, abstract classes…). There is no right tool for a given problem, but depending on the situation, the same problem might be solved using a different tool or a combination of tools.

Nobody knows what they are doing

Nobody has all the answers, we are all in the process of learning to use our toolset and its applications. There are some things you (like me, and like everyone else) will only learn through experience, if you keep your eyes and mind open.

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:


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.


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


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



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


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!