upbeat.it

by Cesare Rocchi

Coding as writing paragraphs

by Cesare Rocchi

There’s an interesting discussion going on in the Cocoa community. It’s about being reactive vs traditional. While reactive programming has been present in the Cocoa community since 2012 with ReactiveCocoa, RxSwift is getting quite some attention lately.

The recent discussion happened between these posts:

There’s more, but that is the backbone of the debate I think.

First of all I love that it has happened between blogs. Authors had room to express themselves instead of yelling at each other 140 characters at a time. And in the future it will be much easier to refer to this debate. I lean towards the traditional solution for three reasons:

  • lazyness
  • lazyness
  • RxSwift being third party

I am not against the use of third party libraries, but I tend to use small ones, usually UI related, and focused on solving a specific problem. This is because I think it’s easier to rebuild them in the future, in case the maintainer drops the support. RxSwift solves a big problem and if I adopt it, I am probably going to make a wide use of it, and it would take much more effort to rebuild it in case I need to.

One thing that touched me particularly during the discussion is

it reads almost like a paragraph

Brent Simmons source

I am trying to write code thinking of my future self and others. That means I am trying to make it readable, and possibly small. I like the conciseness of RxSwift, it just doesn’t click for me at the moment. But I am all in for finding a way to avoid giant networks of classes, that require a lot of time to be discovered and learned. I prefer paragraphs, sequences of paragraphs. Sure, classes won’t go away, but would get simpler internally and externally.

I like promises. Conceptually they are not far from the Reactive approach. In the JavaScript land they are pretty popular. For example this skeleton of code reads pretty natural.

var p = new Promise(
	...
)
.then(function(arg) { ... })
.then(function(arg) { ... })
.then(function(arg) { ... })
.catch(function(arg) { ... })

Of course everything can be complicated at will. For example you could sprinkle convoluted code in any then function, so the skeleton will stretch and the readability will degrade. But still I think it’s a good start.

I like the idea of paragraphs of code that follow this plot:

  • Here’s a sequence of actions
  • During the sequence you will have a container (bag in the case of RxSwift) always handy for your convenience
  • at the end of the sequence you’ll end up with an empty bag, a bag with some items or a bag with an exception/error.

Any approach that adopts a similar “storyline” would solve most of the common scenarios that we deal with day to day, like the widespread “fetch some data according to this user interaction and display the results here”.

I don’t know if RxSwift will be the one solving this problem. But I am glad it’s trying.