Duck Types and Objective-C
I just finished the book, Practical Object Oriented Design in
Ruby. I haven’t been paid to write Ruby code in years and I still found the book incredibly useful. Sandy Metz writes excellent explanations for many things I have felt about code I have seen while working on projects.
In the last chapter, Sandy discusses how to write effective tests. She walks through creating tests to document “duck types” by writing tests that make use of
assert_responds_to. I think with Objective-C these tests are unnecessary for the most part. In Objective-C we can formalize these “duck types” with Protocols. This way the compiler will tells us when our object fail to implement the interface other objects expect. You know, assuming we don’t ignore the warnings coming from the compiler.
A “duck type” gets is name from the phrase, “If it looks like a duck and quacks like a duck, it must be a duck”. The idea is that you can write code that doesn’t care what something actually is, so long as it responds to the right messages. This makes for loose coupling between objects because each object doesn’t have to know exactly what type of object it is working with, simply that it will respond to a certain set of messages.
In theory, you could just use retro Objective-C tactics and declare
these “duck types” as
id instead of
id<RWSTypeProtocol>. This is basically what Ruby does, objects technically have a type, but since you cannot specify the expected type of inputs to Ruby methods, there’s nothing to let you know when the wrong kind of object has been put in the wrong place.
When we make use of the constructs provided to us by the language in
Objective-C, we can eliminate the need to write tests that assert that our objects adhere to the “duck types” we expect them to. This is what protocols are for. As long as we make use of them, create them, use objects that adhere to them, and pay attention to the compiler’s warnings, we can write loosely coupled code that doesn’t need to be verified with tests. Who doesn’t like writing less tests? Certainly not this guy.
This is why you shouldn’t arbitrarily typecast things in your
Objective-C code. Typecasting tells the compiler, “shut up, I know what I’m doing!”. See you know what you’re doing right now, but you from 6-months-from-now might not. Certainly the new guy who now works on your project has no clue what you were doing.
- Embrace the language you’re writing.
- Avoid typecasting
- Make use of its advantages and avoid its disadvantages - Learn from the patterns and styles from other languages, but consider how they might not work exactly the same in the language you’re currently writing.