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:

Swift

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

enumRole{

caseDeveloper

caseSystemsArchitect

caseDevelopmentManager

caseProductOwner

}

classEmployee{

private(set)varname:String

private(set)varrole:Role

private(set)varsalary:Int

init(name:String,role:Role,salary:Int){

self.name=name

self.role=role

self.salary=salary

}

}

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

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.

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:

Swift

1

2

3

4

5

6

7

8

9

10

11

12

enumApplianceForSale: Int{

caseVacuumCleaner=0

caseWashingMachine

caseDryer

caseDishWasher

caseCofeeMaker

caseWaterBoiler

caseFridge

caseToaster

caseWaffleMaker

caseRiceCooker

}

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.

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

Java

1

2

3

4

5

6

7

if(aAnimal instanceofFish){

Fish fish=(Fish)aAnimal;

fish.swim();

}elseif(aAnimal instanceofSpider){

Spider spider=(Spider)aAnimal;

spider.crawl();

}

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.

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:

Java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

classCar{

privatefinalStringname;

publicCar(finalStringname){

this.name=name;

}

publicStringgetName(){

returnname;

}

}

classSafeCarextendsCar{

privatefinalCar actualCar;

publicSafeCar(finalCar car){

super(car.getName());

this.actualCar=car;

}

publicStringgetName(){

returnactualCar.getName();

}

}

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

Java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

classCarWarehouse{

privatefinalMap<String,Car>stock;

publicCarWarehouse(){

stock=newHashMap<String,Car>();

buildStock();

}

privatevoidbuildStock(){

stock.put("Porsche",newCar("Porsche"));

stock.put("Ferrari",newCar("Ferrari"));

}

publicCar getCar(finalStringmodel){

finalCar valueInStock=stock.get(model);

Car returnValue;

if(valueInStock==null){

finalCar nullCar=newCar(model+" is out of stock");

returnValue=newSafeCar(nullCar);

}

else{

returnValue=newSafeCar(valueInStock);

}

returnreturnValue;

}

}

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.

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.

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:

Shell

1

$git pull origin

You can create a “local” alias:

Shell

1

$git config alias.popull origin

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

Swift

1

$git po

And voilà.

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

Shell

1

$git config--global alias.popush origin

And voilà again.

My favorite? This one:

Shell

1

2

$git config alias.last'show -s HEAD^commit'

$git last

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:

Shell

1

$git checkout master

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

Shell

1

$go master

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

Shell

1

$pico/.bashrc

Now add the following alias to that file:

Shell

1

aliasgo="git checkout"

Save and exit, and force bash to refresh:

Shell

1

$./.bashrc

(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)

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:

Shell

1

$git tag-av1.5.RC1-m'version 1.5 Release Candidate 1: iPhone support'

Tags can be listed:

Shell

1

$git tag-l

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:

Shell

1

$git tag-l-n1

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:

Shell

1

$git tag-l'v1.5.*'

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:

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…

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.

Swift

1

2

3

4

5

6

7

8

public overridefuncrestoreUserActivityState(activity:NSUserActivity)

{

//don't forget to call super!!!

super.restoreUserActivityState(activity)

letuserInfo=activity.userInfo

loadDataWithCategory(userInfo["category"])

}

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