Skip to content

The Amazing Adventures of a Sexy Software Engineer Posts

Modularity in layman’s terms

Imagine that every Sunday you have the opportunity to design your week schedule.

Now, imagine that you are only allowed to design your schedule by combining pre-built blocks, and that you are given blocks like those in set A.

Screen Shot 2016-04-19 at 12.08.21 PM

And now imagine you can choose from blocks like those in set B

Screen Shot 2016-04-19 at 12.08.29 PM

Which set of blocks will allow you to build a more flexible schedule? Would the schedule built with blocks from set A be more or less difficult to adapt to change that the schedule built with blocks from set B?

That’s modularity. And that’s why the single responsibility principle matters. And that’s why methods should not be long. And that’s why classes should not be long. And that’s why view controllers that control views, do networking, and contain logic to deal with navigation are bad.

Leave a Comment

It’s the open-closed principle!. Duh!

So, this has been my “facepalm moment” of the week. Not the only one I had this week, but the most remarkable one.

I was trying to explain what the Open Closed Principle is all about to a colleague. You know, “modules should be open for extension, but clsoed for modification”. You know, the good stuff.

As usual, I was trying to find a good example to illustrate the point of the OCP, and as usual, I was having a hard time finding it. Side note: finding good examples to illustrate abstract concepts is hard; if the example is too simple, everyone misses the point, if the example is too convoluted, everyone falls asleep.

And suddenly, the duh-facepalm-eyerolling moment! How can I be so dumb, the perfect example of the OCP is sitting right there, looking at us!

Extensions!

So, here comes the example (not too simple but yet not too convoluted) to illustrate my point.

Imagine a model object:

Now imagine we have a mechanism for transporting model objects across the wire, based on JSON:

Well, we want to be able to send Contacts using this JSONDataSender, so we should make Contact implement the JSON protocol, right? True, but devil is in the details, and in this case, the simplest solution would require modyfing the source code of the Contact struct to add the new behaviour:

Which would be a blatant violation of the Open Closed Principle (the object had to me modified in order to add behaviour to it). Tsk, tsk, tsk…

What’s the problem with that approach? Well, we might want to serialize to a protocol buffer, instead of JSON. Or write Contacts to a plist file, or to a SQLite database, or whatever. So every time we wanted to add that extra behaviour, we would need to edit the Contact source. Again, tsk, tsk, tsk.

However, if we don’t modify the original Contact, but add an extension:

We would have extended the object without actually modifying it. Again, the object would be open for extension and closed for modification. And adding subsequent behaviours would be a matter of adding more extensions. So, to me, and from now on, this counts as the perfect example to illustrate the Open Closed Principle (in Swift).

Leave a Comment

Binding custom view properties with RxSwift

Lately, I have been dipping my toes into the world of reactive programming. To be honest, I should probably say that I’m up to my neck into it: ReactiveCocoa, MVVM, “everything is a stream”, and all that.

In my spare time I’m looking also into RxSwift. Even though this blog is mostly about Swift, I spend a significant amount of time writing code in other languages (mostly Java, Scala and C#), so it makes sense to learn what seems to be a more cross-platform approach than the one ReactiveCocoa follows. Platform agnosticism FTW!

But, back to the point of this post. Remember the Ring we discussed in the previous post? If you don’t, well, it’s basically a UIView subclass, that exposes a few public properties to make it configurable. Today I am going to focus on just one of them: progress.

The Ring class is part of the UI of a little pet project of mine, where I want to display some data I fetch from an async service. After fetching that data, I want to update a progress ring (my Ring class) and a label.

 

reactive_ring

So, in the good old days, before my reactive enlightenment I would probably do something like this: (for context, this is the view controller that manages the ring and the label)

For the sake of completing the example, the signature of the method in the data service would be like:

So, not too bad, I guess. An async service, a completion closure as a parameter, and done.

But, if there is a use case for reactive programming, that would be dealing with async stuff. So, let’s go Rx!

The method in the data service signature could look like this:

And now, in my view controller, I could do something like:

Not too bad! But it could be better. This code is still a little bit imperative. It is not a big deal, but I think it would look better, be more readable, and in a way easier to maintain, if I could bind both the ring and the label to the result emitted by the data service observable.

Binding to a UILabel is easy, RxCocoa provides extensions for that, but binding to a custom property in a custom view is obviously not provided out of the box.

But fear not, because it is very easy to do. As easy as the following:

So now, back to my view controller, I can bind the Observable directly to the ui controls, transforming the values emitted by the data service, in just one go:

And done!

Leave a Comment

Building a custom ring

A pet project of mine requires replicating one of the progress indicators in the Health app. I want to be able to configure the ring’s thickness, colour, and percentage of completion.

Before launching Xcode and start writing code right away, I wrote down what I knew about the problem I wanted to solve:

  • CAShapeLayer seems to be a good fit for this.
  • Animatable properties are, well, animatable. And for free. All you need to do is set their new value, and core animation will take care of animating the transition for you.
  • It is easy to build an oval UIBezierPath.
  • It is easy to apply transformations to bezier paths
  • It should be possible to configure the view both programatically and in Interface Builder.

With that in mind, I decided to build a subclass of UIView, insert a CAShapeLayer into it, and bind the “progress” property of my view to the layer’s strokeEnd property. Also, I decided to took this as an opportunity to explore @IBDesignable and @IBInspectable, which is something I’d never done before.

And this is the end result:

animation-small

The source code is available on GitHub, but let’s take a look at some of the highlights.

Display a custom view in Interface Builder

This one was easier than I expected. I can not claim to be an expert in Interface Builder, so I expected a lot of friction here, but annotating the class as IBInspectable was enough to make Interface Builder aware of it:

Making the view configurable through interface Builder (as well as programatically) was also quite easy, just by annotating properties as IBInspectable and providing a default value for them:

Building the actual ring

There might be a better way to do this -I’m looking at you, UIBezierPath(arcCenter, radius, startAngle, endAngle,clockwise)- but I decided to rely on the fact that UIBezierPath’s strokeEnd is animatable (which means that everytime I cahnge its value, CoreAnimation will animate the changes for me), so I built the path as an oval, and set the strokeEnd to the value of the progress property (which is normalized between 0 and 1).

Of course, that makes the path start at the X axis, so the path’s layer needs to be rotated -PI/2.

After that, it is just a matter of setting the proper frame, and path in the layoutSubviews method. Here is the relevant code:

The full source is available on GitHub, and can be pulled in as a dependency through Carthage.

1 Comment

Swift Class Clusters

There was an interesting discussion at work today that led to class clusters.

First, I was surprised by the fact that, apparently, class clusters are something only old farts like me are aware of. But the discussion got me wondering: would it be possible to implement a class cluster in Swift?

Well, apparently it is. Let’s say we want to consume this cluster within the module it is declared in. So, by relying on inner types, we coudl do somenthing like this:

So, now we could do something like this:

Now, the question is: would I ever do this in production code? I am not sure. Are there better ways to simulate a class cluster? I assume there would be, so if you know about them, please shout out in the comments!

Anyway, for those interested, there is a sample project on github

Leave a Comment

Devil is in the details II: immutable collections

Inmmutability is good. Just yesterday, we were discussing how good it is. But just in case, here is another example.

Let’s assume we are building the software to manage a company’s payroll. We have only these requirements:

  • The Human Resources Department should be able to hire and fire people.
  • The Human Resources Department needs to validate that a Person has a valid id before hiring her (there are very strict immigration regulations in here).
  • The Human Resources Department should be able to produce an up-to-date list of employees at any moment in time.

The simplest thing that could possibly work

With those requirements in mind, this the simplest thing we can build. A Person would look like this:

And the Human Resources Department would look like this:

Notice how we do some fancy validation when hiring a new person, and throw an error if anything goes wrong. Also notice how the employees arrary is public, because HR need to produce it upon request.

The devil is in the details

We can hire someone:

We can try to hire someone without a valid Id, and HR would throw an error:

But, we can also bypass the ID validation by modifying the employees array directly:

Boom!

Public collections should be immutable

This is, obviously, a very convoluted example. But the thing is that when we do not enforce immutability, bad things may happen, either by distraction, by means of unexpected side effects, or just by means of malicious or misbehaving code.

One way, and it is not the only possible way, to enforce immutability in the precious example might be this:

Notice how we made the mutable collection private, and we provide a readonly property (employees) that returns an immutable collection, built upon request. But, remember, what matters here is not how we create that immutable collection, but the fact that the public API of the HR class provides only immutable data.

5 Comments

Devil is in the details: final vars and methods

Immutability is good. I have discussed this issue, briefly, in this blog in the past, and it won’t be the last time we discuss it.

Today, we are going to look at how not enforcing immutability can have undesired and unexpected side effects.

Let’s consider this class:

Now, let’s assume that Human Resources calculates monthly payslips like this:

So, this could happen:

Boom!

One solution would be making the Developer a struct or a final class. But for the sake of the argument, let’s say that making that class final is not a possibility, because we actually need to subclass it. Which is not a rare use case, by the way. Not everything can always be final, even if it probably should.

In this case, one solution might be declaring those properties as final:

The point of this post is that the defaults (default access modifiers, default read/write access) are not always the best. And that we need to be aware of what might happen when we rely on the defaults.

And, most importantly, unexpected see effects are avoidable. And we should avoid them.

1 Comment

Generic datasources and cells. Introducing FountainKit.

A couple of months back, I published a couple of posts that seemed to rise some interest (for this blog’s standards), about unit testing collection and table view cells, and leveraging generics to implement collection view datasources.

Huge, monolithic view controllers are not good for any codebase

A view controller, like any other class, should have only one responsibility. However, often times, view controllers do too much: layout views, deal with user interaction, load data from the network, and prepare data to be presented by table views and collection views.

Let’s take a closer look at that last responsibility: preparing data to be presented by a table or collection view. That usually happens by means of implementing either UITableViewDataSource of UICollectionViewDataSource. Just to simplify the discussion, let’s say that often times, view controllers behave as datasources.

The problem with that is that we are adding a responsibility to an object that is already doing too much. In fact, it is not just responsibility, but multiple ones: the view controller would need to be aware of the structure of the data that we want it to present, it will have to be aware of how we want to present it (since we usually populate public cell outlets in the implementation of the cellForItemAtIndexPath method), and since it is already aware of the data structure, it is very likely that it will also handle user interaction with the table/collection, and therefore it will also be responsible for navigating to another view controller, or performing network request.

That’s too much. Those are too many reason why the code in that view controller might need to be changed, those are too many things to get right in just one object. And code that does too much is error prone and difficult to maintain.

So, now that we have established that we don’t want view controllers doing too much, and in particular that we don’t want view controllers acting as data sources, what can we do to avoid that scenario?

Divide et impera I: Data

As usual, the solution is breaking the problem down into smaller pieces. Highly cohesive pieces.

We need to fulfil three responsibilities: manage a data collection, prepare cells according to the way we want to represent the data in that collection, and render that information on screen. So, we have three distinct responsibilities, but somehow related by the kind of data we want to present on screen.

First order of business would be encapsulating the management of the data collection. We want to do it in a way that allows us to manage strictly-typed data, without knowing exactly the type of our data. Well, that’s what generics are for, don’t you think?

But we also want to be able to manage different data structures in an abstract way. Well, that’s what an interface (protocol) is for, don’t you think? 😏

So, this would be our starting point.

Now, we can have an implementation of that protocol that manages a single section data structure (AKA flat array)

Divide et impera II: Cells

Cells are the only entities that should be involved in actually rendering information on screen. If we think of data in one end of the pipeline, cells would be in the other end.

Cells are pure UI. Actually, me might see them as tiny little view controllers, with one responsibility: populate outlets (i.e. labels and image views) with data, doing that in the simplest possible way (that means, directly assigning values, without being concerned by any other business logic)

Again, have in mind that we are sending a data object (model object) through and imaginary pipeline that starts in our data structure. And, have also in mind that, as usual, we want to be able to provide different cells, all of them sharing the same behaviour (being able to accept a data object of a generic type)

In order to achieve that, we will make our cells implement this protocol:

Divide et impera III: Binding data and cells

Well, that’s what data sources are for, aren’t they?

A datasource is nothing more that the entity that is in a position to know which cell needs to be presented on screen, grab the cell and the data object that needs to be presented, and force them to talk to each other.

If we think about this whole thing as a pipeline with the data model in one end and the cells in the other, the datasource would be the actual pipeline, it would be the glue that binds data and presentation together.

Let’s declare a class that implements UITableViewDataSource. We are only going to implement the required methods of UITableViewDataSource, so we will not make this class final. If, eventually, in an specific project, we need to implement more methods of the data source protocol, we can subclass.

Also, we want to bind a data collection of type T with a cell that implements a var of type T (remember, we want to be able to provide the model object to the cell).

So, this would be the declaration of our datasource class:

Notice the generic constraints: we want this class to be qualified by two generic types, but we want the first of those types to implement DataManager, the protocol that abstracts our data collection, we want the second type to implement DataSettable, the protocol that abstracts our cells, we want the second type to be a subclass of UITableViewCell, and here is the tricky pat, we want the associated type declared in the DataManager protocol to be equal to the associated type declared in the DataSettable protocol.

Now, that’s all good, but we need one extra step in order to make all the pieces fit together. In the data source initialiser, we declare two parameters, the data manager, and the cell type. Notice how we do not retain the cell type, we only pass that parameter to make sure that the generic constraints are enforced.

Divide et impera IV: The benefits of dividing, aka conquer.

It could be argued that all of this is nothing more that a gymnastics exercise on generics. But there are some significant benefits to it:

  • Better testability. This approach makes the cells, the view controllers and the datasources easier to test.
  • Better separation of concerns. This one goes hand to hand with the previous point. When there is good separation of concerns, things are easier to test.
  • Higher cohesion, and lower coupling. We broke the problem into smaller, highly cohesive pieces. Each piece has one and only one responsibility.

Introducing FountainKit

I have been using this approach in my projects for quite some time now. It works well for me, and I thought that it might work well for others.

So I have packed some of my code into a framework, and published it to Github, including a sample project that shows how to implement an actual table view:

https://github.com/ctarda/FountainKit

There are plenty of improvements to make, but there is nothing like receiving feedback (Agile mindset FTW!) to build software that solves actual problems.

2 Comments

Swift Package Manager and private github repos

The last couple of days I have been exploring the possibilities of building a REST API in Swift for a pet project of mine. I have been trying to deploy it to Heroku, following the instructions in this post.

Now, I want to share some code, that I want to deploy as a Swift package, between my client side and server side projects. And that shared code lives in a private repo in github.

So, there are two ways to do that (there might be more, but I am only aware of these two).

First, expose the username and password in the Package declaration.

Obviously, this is not good.

The second one, is by authenticating with a personal access token. Personal access token are available in github’s Personal Settings > Personal access tokens. What seems to work for me is selecting “repo” as scope (which includes repo:status, repodeployment and publicrepo)

Adding the token to the Package manifest like this:

allows Heroku to check my private repo out and build my project every time I trigger a new deployment.

If you know of a better way to do this, please sound off in the comments!

Leave a Comment

What I like about Swift

Lately, I have been interviewing again, only this time, being the interviewee, not the interviewer. The experience has been quite interesting, to say the least, and probably deserving its own post, but I would like to focus today in just one aspect of it.

Since I have been working on Swift-only projects almost exclusively since it was publicly released in 2014, one recurring question in every interview has been “what do you like about Swift”?

Now, before digging into what I like about the language, here comes the disclaimer:

Disclaimer.

This post is not an attempt to enumerate everything that is good with the language. This post is just a list of things I like about the language, things that make me more productive, or that make me write what I regard as better code. YMMV, so please take this only as my reflection on the code I’ve read or written during the last year and a half, and what I liked about it.

So, in no particular order, this is what I like about Swift:

1. Safety

This is a very broad topic, so I am going to break it down into smaller chunks.

Let’s begin with…

1.1. Swift code crashes very rarely

Maybe it is not because it is Swift, maybe it is because I am actually getting better at my craft after so many years, but I have the feeling that this one should be pinned on the language, not me.

Judicious use of optionals, specially as return values of integrations with remote APIs, in combination with judicious implementations of the Null Object pattern here and there make dealing with unexpected data almost pleasant. Almost.

But the point is: I have found that using optionals, when it makes sense, makes the code safer, and makes apps very difficult to crash. Which I assume is what the language designers had in mind.

1.2. The Swift compiler enforces safety

I know we all come from a background where swizzling and typing stuff as id where considered acceptable, when not good practices. And I am the first one that, sometimes, has wished that the Swift compiler got off my back, but, in the long term, I have found strict type safety to be one of the best features of the language, hands down.

Having someone telling you to not do something stupid before you attempt to do it is priceless. Seriously, I don’t consider strong typing a limitation, but the opposite.

2. Swift code is more modular

Again, this might very well be case that I have started to actually understand what all this Software Engineering thing is about. But I tend to believe that Swift actually helps build simple, decoupled code.

Extensions, and protocol extension in particular, make easier to rely on composition instead of inheritance when it comes to modelling abstractions. That makes the code way less rigid, and therefore way more modular.

I find very easy to build abstractions not by looking at what things are, but by thinking about how things behave. And I find behaviour way easier to abstract, manipulate and compose.

Modelling behaviours behind protocols, and providing default implementations of those behaviours in extensions has made my life way easier.

3. Richer type semantics

Swift provides classes, but also structs and enumerations. it could be argued that Objective-C also provided structs and enumerations, but structs where a pain in the rear, and enumerations where just sequences of integers.

Now, we can attach behaviour to structs and enumerations. We can make structs and enumerations implement protocols, so we can provide default implementations of those protocols through extensions. Oh, and enumerations can have associated values. I seem to like enumerations a lot, apparently.

A class and a struct look similar but they are not similar at all: one is passed by reference, the other is passed by value. Again, that will make the code safer in many situations.

And did I mention generics? I love generics. Generics are awesome. How could we live without generics for so long? I only wish protocol’s associated types where not that weird. I guess you can’t have it all…

4. Conciseness and simplicity

Swift code looks concise and to the point. I love how the compiler infers stuff for you, so you don’t need to write an enumeration name to use one of its cases, or how you can call .redColor() without the UIColor in front of it, or declare strongly typed arrays without actually needing to write the type explicitly.

It saves time, yes, but it also removes noise and distraction from the code. And I am looking at you now, square brackets. And I am also looking at you now, header files.

5. Access modifiers

In Objective-C, everything was either completely public or completely private (of course, having in mind that nothing was actually completely private)

Now, we can organise the code in modules. And we get to choose if we want something to be public and visible by everyone, or only visible by the module it belongs to, or be completely private and accessible only within the file it is declared in.

That provides an extra level of modularity and safety. Because, remember, encapsulation is good, and encapsulation is only enforced by privacy. And privacy is good.

6. Swift code is cleaner

This one is hard to blame on Swift only. After all, as the old adage says, you can write FORTRAN in any language. In this case, any programmer can write tangled, imperative code in any language. And I have been guilty of that many times. But I have found that all the features enumerated previously provide, as a final result, better code. Code that is easier to read, easier to understand, cleaner, more modular, and therefore easier to maintain and extend.

Which is what this whole “engineering” thing is all about, isn’t it?

What I don’t like about Swift

Xcode can not refactor Swift code. And that drives me nuts.

Final words

As you might have noticed if you have reached this far, there is a lot I like in Swift, and not too much I dislike.

In my experience, Swift code is clean and modular. When I write Swift, I usually find myself in a SOLID-compliant mode.

In one line, what I like about Swift is that it makes writing clean and maintainable code easier, and fun.

Leave a Comment