The Payroll Machine.

Or, as some would say, the story of how some complexity might be necessary sometimes. Or, yet another edition of Looking at the Wrong Abstraction.

The difficult solution

Imagine you need to develop an application that calculates a company’s payroll. Let’s assume that we have three different roles within the company (Developer, Systems Architect, Development Manager, and since this is a modern cool and hip company that does scrum, a Product Owner), and that different roles have different salaries.

The simplest approach

Well, you could argue that it does not actually matter too much, when calculating the payroll, if an employee is a Developer or a Systems Architect. So, one sensible approach might be to model all employees as instances of a class like this:

Now, calculating the payroll is just a matter of doing something like this:

Real life sucks. Or requirements change

I bet you have been there a thousand times. Your app is all app and running, processing data full steam ahead, doing what is expected to do, and doing it well, when suddenly… requirements change.

In this case, the CTO demands a new feature: he should be able to assign multipliers to specific employees, so he can modify their salaries temporarily.

The flexible solution. Or, the mega-awesome although apparently slightly over-engineered solution, that after some consideration, happens to be just awesome and not over-engineered at all

First, I’ll show you all the codez. The I’ll discuss all the codez.

Now, there are different kinds of Employees. To me, that means that each of those “kinds” has to be modelled by a different class. Why? Because they represent different behaviours. As you know, a PO does not do the same things a Developer does.

However, it is true that I am only interested in part of the behaviour of those different kinds of Employees. That is already abstracted by the interface!

Is there repetition? Yes, apparently, but I wouldn’t call it repetition, I would call it specialisation. If there is something else to be taken into account when calculating a salary (for example, manage,went might have part of their salaries payable in shares dividends and whatnot), the specific class that models a PO can implement that specific behaviour.

Also, this solution improves encapsulation. The responsibility of calculating each employee’s salary is well encapsulated, and is completely opaque to the calculatePayroll method.

Summary

Often times, a flexible solution requires more code than a simple one. Well, that’s life, I guess: if you want something done properly, you will need to put some serious work into it. It does not matter if it is installing a new fridge in your kitchen, or writing a new method in your code.

But the key here, again, is that being able to identify the right abstractions makes a huge difference in the scalability, modularity and cleanness of your code.

Swift tip: enumerations are first class types

The Book says it without any doubt:

Enumerations in Swift are first-class types in their own right

But wait, there is more! (I love the way my blog’s theme formats quotes, so I

Enumerations in Swift are first-class types in their own right. They adopt many features traditionally supported only by classes, such as computed properties to provide additional information about the enumeration’s current value, and instance methods to provide functionality related to the values the enumeration represents.

But wait, there is even more!

Enumerations can also define initializers to provide an initial member value; can be extended to expand their functionality beyond their original implementation; and can conform to protocols to provide standard functionality.

Yes, if you ever had to write Objective-C for a living, sooner or later you would find yourself in a spot where you would need to loop all the values in an enumeration.

It was not a big deal, because, well, Objective-C enumerations where collections of integers. So all you had to do was end the enumeration with some sort of marker, that indicated you that you were done.

Well, Swift is different. And this time, that’s for the best. Consider an enumeration like this:

Would there be any safe and maintenable way to loop all the values in that enumeration? Indeed, there would be, thanks to Swift’s Sequences and Generators.

Sometimes nothing is something. Or the null object pattern with a touch of the decorator pattern

Or why if clauses should die in a fire.

This post has been lingering, locked up in my drafts folder (which is not an actual folder, but all the cool kids say that, so bear with me on this) for some time.

Yesterday, I stumbled upon this talk by Sandi Metz, because, yes, sometimes I search Youtube looking for recordings of talks about OOD. I am a big fun on Sandi’s talks, and this one did not disappoint me, as usual. And it also gave me the push needed to publish this post

If clauses breed, and sometimes, nothing is something

I am not a big fan of if clauses. I know they are necessary, but I try to avoid them as much as possible, specially when they are type checks.

Type checks are bad

Period. There is always someone that will tell you that type checks might be necessary sometimes, but truth is they are one of the biggest and stinkiest code smells.

“What is a type check?” you might ask. Fair enough; this is a type check:

This is the quintessential example of why type checks are wrong, and you will find a thousand slightly different variations of it on the interwebs.

What’s wrong with that? Simple

Type checks are a sign of bad design

The previous code sample is the perfect example of how a type check is a symptom of a bad abstraction. A Fish and a Spider are both animals, so they both should implement an interface declaring a move() method. Clients of Fishes and Spiders would only be aware of that abstraction and call the move() method. Period.

There is a particularly bad type of the check

And that is the one that does not look like one. It is usually in disguise, pretending to be a null check.

Here is an elaborate example. Consider a Car class:

And a CarWarehouse class:

Now, clients of the CarWarehouse want to checkout cars by name:

The forEach method will crash, because it is trying to call getName on something that is null.

Fine, you might think, I will just filter the stream to remove the objects that are null:

But that’s just bad.

Type checks breed

Once you need to start filtering your results, once a client of a class A needs to start performing a type check on the values returned to it by that class, you are going to need to repeat those checks every single time you want to use that class A.

Why? Because you expect the values returned by A to be of at least two different types: null and whatever it should actually be returning.

So, how what can I avoid those type checks?

Making your classes meet the expectations they set. Simple as that.

Which, of course, happens to be not that simple. But seriously, if clients of your class are expecting a collection of entities that respond to a particular message (note the Smalltalk-speak), make sure that all the entities your class returns respond to that message. Again, simple as that.

In the previous example, what do I want exactly? I want all the objects returned by CarWarehouse to respond to getName. Then all I have to do is return a collection of objects that respond to getName. And if there is no object to return, then I will return something else that still responds to that message.

The Decorator pattern. Sort of.

Here come the big guns! Design patterns to the rescue! Not too long ago, I ranted about how design patterns are abused.

In this particular case, I m going to adapt one of the patterns in the catalog, the Decorator Pattern, to wrap my Car objects:

Notice how SafeCar extends Car. That allows me to do the following:

Which, as you can see, is basically creating a null object, sort of. Again, I am taking the liberty of adapting the pattern to my needs.

And now, clients of my CarWarehouse can conduct their business merrily:

Summary

What matters are not the tools you have, but how you use them. Over-abstraction is bad. Over-engineering is bad. Knowing the tools in your belt, knowing how to adapt them and how to let them work together to solve your needs is what matters.

Oh, and sometimes, you need something to help you deal with nothing.

Brew tip: linking to a specific version of a package

Homebrew is awesome.  If you are a developer, and use a Mac in your daily adventures, you should install it. Period.

This little tip might be handy, specially when you want to rollback to a previous version of a package after an update. Because, you know, shit happens, and more often than not, updates break stuff.

You can list all the versions of a package installed in your system:

And to force the system to use a particular version:

 

KISS and YAGNI FTW!

Acronyms galore!

If you have read any other post in this blog you might have noticed an emerging pattern: I like simplicity.

Over-engineering much?

I bet you have read the following quote before, in any of its multiple forms

A junior engineer creates complex solutions to complex problems, an more experienced engineer creates simple solutions to simple problems, and a senior engineer creates simple solutions to complex problems.

I would reduce that to something even simpler (see, the same pattern again)

Some engineers create simple solutions, some engineers create complex solution. The complexity of the problem does not actually matter.

In my experience, there is an inflection point in every developer’s career, right at the spot where said developer first encounters design patterns. Suddenly, the whole world becomes a playground, where everything can and will be modelled as a use case of a design pattern.

Don’t get me wrong. There will be plenty of life-changing moments in a developer’s career, but this one affects each and everyone of us at some point or another.

Design patterns

Design patterns are solutions to problems that you will find again and again. Every developer should know their patterns. They provide a shared language, a lexicon, so to speak, that allows developers to describe a problem in a few words. Phrases like “that’s a command” or “use a factory for that” should provide enough information for any developer to know what to do.

But…

As usual, “the virtue of justice consists in moderation”. If is very easy to turn into a pattern-freak, and start seeing patterns everywhere. That syndrome, if left unattended, can lead to a serious disease: over-engineering.

The problem: over-engineering

This is, sadly, an unrecoverable disease. Some symptoms are using interfaces that extend tag interfaces to type method parameters, trying to turn everything around you into a UML diagram, using the term “business domain” more than once in a single week, and generally speaking, writing code that solves problems that you don’t have.

The solution: keeping it simple

Here is where all the fancy acronyms in the post title come into play. KISS (Keep it Single Stupid) and YAGNI (You Ain’t Gonna Need It) are two terms easy to remember and understand. But in a way, both can be reduced to a very simple principle

Occam’s Razor

Occam’s Razor is a problem-solving principle devised by a William Ockham. There are a thousand variations of the principle’s formulation, but I am extremely fond of this one:

Frustra fit per plura quod potest fieri per pauciora (It is futile to do with more things that which can be done with fewer)

In other words: less is more.

Simplicity FTW

There are many benefits in not over-designing or over-abstracting at an early stage.

It is very difficult to see deficiencies in overly complicated code

Well, sometimes the trees don’t let you see the forest and so on and so forth. Complicated code is difficult to read. Too many abstractions make difficult to follow the flow, to understand what is happening.

However, when dealing with simpler code, all the deficiencies will be extremely easy to identify.

Allowing some duplication at early stages simplifies the design

DRY FTW! Sure, but sometimes, a little bit of D is precisely what you need in order to identify what you should abstract and generalise.

You can not foresee the future.

If you could, you would have probably won the lotto by now, and you would live a happy life. However, here you are, reading this.

Adding layers upon layers of abstraction to accommodate future changes in the system is fun, and makes you feel smart, but it is very likely that many of those layer will not be actually necessary.

In a month’s time, you will have to read the code you write today.

Right before extracting that interface that declares just one method that receives something typed as another interface as parameter, ask yourself: “will I still understand what I did here in a month’s time?” If the answer is no, well, you know what not to do.

Summary

Life as a software engineer is complicated enough as it is. Adding to many abstractions too early might make things too complicated.

Object Oriented Design is all about trade-offs. Often times, the simplest possible solution is the best one in the long term, even if it is only because it makes your mistakes and bad decisions popup immediately at you.

Keep it simple!

There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.

C. A. R. Hoare

Git tip: aliases

The title is a little bit misleading, because this post is going to cover both a Git and a Bash tip. But this is my blog, so I title my posts the way I want.

Please, bring on some tips!

This is a tiny little trick that may be useful only if you ask Git to fulfil your wishes using the command line. Which you should probably be doing at this point, if you want to call yourself a real developer.

Git commands are totally long and totally hard to remember. True. But what if they could be shortened?

Well, in a way, git commands can be shortened. Or at least, adapted to your personal preferences, thanks to aliases.

Aliases can be global or specific to a repository. For example, if you are bored of typing:

You can create a “local” alias:

And from that moment on, you can just do this:

And voilà.

If you want to apply the alias to all your repos:

And voilà again.

My favorite? This one:

Cool, but what about the bash tip?

Yep, I have one of those as well.

bash (the only true Unix shell) allows the creation of shortcuts to certain commands, called alias. For example, if you find yourself typing a thousand times a day the following command:

Wouldn’t it be neat to be able to just type the following?

Well, that’s easy to do in just to steps. First, edit the bash configuration:

Now add the following alias to that file:

Save and exit, and force bash to refresh:

(Note the space between the first dot and the curly-thingy-that-we-use-in-Spanish-on-top-of-the-letter-n-to-make-it-sound-funny)

Now, when you want to checkout a branch, just do:

Ain’t that neat?

Git tip: finding a tag by annotation

Git tags can be annotated. An annotation is a message that will be associated to the tag, and that can be used to embed some extra information that might help remembering, months later, why you decided that a particular commit was worth tagging:

Tags can be listed:

But the result is a little bit disappointing, specially if you added annotations (hint: annotations will not be shown).

If you want to see your extra-meaninful messages added to your tags, you can do something like this:

That basically provides either the annotation or the first line of the latest commit message associated with each tag.

You already know that searching for a particular tag, by tag name, is easy:

But, what if you only remember part of the annotation, and you want to know the tag it was associated to? Well, it’s a matter of combining some of the previous examples, and a little bit of grep-foo:

And that is one way you can search tags by annotation message.

A beginners guide to implementing Handoff

Handoff is one of the coolest new features in OS X Yosemite and iOS 8. It allows me to do cool stuff like start composing an email in one device and finalising and sending it in another.

Magic? No! All it takes in some adventurous development backed up by the proper amount of tea or coffee.

How does it work?

Thanks to a combination of NSUserActivity and the OS that sends instances of those activities back and forth between devices. But that is not the best part. The best part is that NSDocument, UIDocument, NSResponder and UIResponder (and therefore all UI classes on both OS X and iOS) have a new property called userActivity which is, surprise, of NSUserActivity type.

So basically, all you have to do, is create a new instance of NSUserActivity in the view / view controller / window / document that you want to be advertising itself as allowing Handoff. The system will take care of sending that activity to other instances of your app in other devices.

After that, you will also need to add a couple of methods to your application delegate, and done!

By the way, Handoff is allowed between multiple instances of iOS apps, between iOS apps and OS X apps, and even between apps and websites.

Neat! How can I support Handoff in my app?

In order to be able to implement Handoff in your Mac / iOS app, all you need to do is…

Declare your activity types in the app’s Info.plist file

A picture is worth a thousand words, so:

Screen Shot 2015-04-07 at 14.16.00

Create activities

Not that kind of activities.

A view controller that wants to expose itself as “continuable” might do something like this:

The system will call becomeCurrent in the view controller automatically if said view controller is in the view hierarchy, but if it is in transition, it will call it after the transition has been completed. Why should you care about that? Because calling becomeCurrent, starts advertising the activity (which is what you are supposed to want, by the way).

Also, when the view controller is removed, or in general, when the system decides that the activity is not needed anymore, it will call invalidate in the activity.

Put information in the activity

Usually, you would want to put some context into the activity. After all, that is the way you will be able to recreate the state in the destination app. You can do that by putting information in the activity’s userInfo dictionary.

In order to do that you should override updateUserActivityState in your UIResponder subclass:

You can put in that dictionary anything that can be serialised to a plist file, in other words, the usual suspects: NSArray, NSDictionary, NSString, NSURL… you get the idea. Be frugal, though, the information you put in the dictionary has to travel the interwebs to reach other devices, you might want the payload to be as light as possible.

Allow your app to reconstruct its state from an activity

This is the neatest part of the whole thing. In your app delegate, the system will call application:willContinueUserActivityWithType. That’s the moment when you need to provide visual feedback to the user indicating that something is about to happen. For example, that would be the perfect moment to start transitioning to a new view controller.

Now, for each call to willContinueUserActivityType, the system guarantees that there will be a call to either a success or an error handler.

The success handler will be called when the system fetches the user activity. The system will pass a block that you will have to call yourself, passing it an array of whatever you want to respond to that activity (in most cases, that would be an instance of the VC you created in the previous step).

Now, in your MainListingViewController, the system will call restoreActivityState. That’s where you can recreate your UI state, according to whatever you receive in the activity’s userInfo. You can also call this method manually if you need to.

If the system can not fetch the user activity, instead of continueUserActivity, it will call didFailToContinueUserActivity in your app delegate

Summary

I would definitely recommend spending one hour watching the relevant WWDC video, and checking out the Handoff Programming Guide.

Handoff is one of the major new features in the latest iteration of Apple’s Operating Systems. It is easy to implement, and the results, in terms of user experience, are definitely worth the effort.