Clean Networking Code
I can’t help but think that my networking code was cleaner before the introduction of blocks, before 2010. That doesn’t mean my networking code after that date sucks though :)
One of the things I liked the most when I discovered Objective-c and the Cocoa frameworks was the delegate pattern. I saw it and it clicked, just like that. To give you a bit of context I was coming from the world of Java, writing code to generate factories that in turn generated factories. Not exactly fun.
One thing that bothers me when I write code is switching between files. When I want to quickly make something that works, I put everything in a class. When it works as expected I refactor and split responsibilities into classes. I feel the result is more clear when I follow that process.
When I learned the delegate, keeping three files open wasn’t an annoyance, because the pattern was so clear to me. Object A asks Object B to do something, and when B is done it will tell A. And the cool part is that I can define the “vocabulary” that A and B use to communicate. Nitpicking, the only thing to pay attention to is the way objects are connected, weakly or strongly. But it is usually declared in one place, a property, easy to find and change if needed.
With delegates you had just one way to screw up with the memory, when you declared the weak or strong ownership. Whereas within blocks, every time you use
self, you have a chance to create a leak.
I tend to like patterns when there are fewer things to remember and fewer chances to screw up. To provide a bit of context on this I am mostly a Product Programmer so code is a means to build something, the less attention I put on the means, the more I can put on the product.
A few days ago Marcus Zarra posted an interesting design for networking code, that clicked with me much like the delegate pattern did.
It’s based on
NSOperation. I was already planning to adopt the approach suggested by Apple in the Advanced NSOperation talk last year, but the one of Marcus is even more clear. In both cases network operations are small units, confined and testable. A design that fosters composability, which I like a lot.
I plan to build the networking code for the Podrover iOS app adopting this approach. It’s gonna be fun.