Partial vs. Complete Functions  

Whoo boy, stick with this seemingly complicated article (linked in the title), because it directly addresses that subtle issue that I face regularly when functions or methods that I write can’t properly map directly all input to your desired output.

This reminds me of a great, simple bit of writing by (I think) David Smith regarding optionals in Swift. Of course, I can’t find it. But the point of that article was that the elegant thing about optionals is that it codifies the fact that all objects are not only subject to having a variety of values but also subject to being assigned a value or not. Making this fact explicit and requiring the author of the code to handle it, leads to better, safer code.

The article in question here is worth reading, even if parts of it are too “academic”. His simple examples really make it clear.

Basically what he is arguing for is that you should not write functions that require some form of assert (a precondition) in the beginning to make sure that unacceptable input is being sent to the function.

Using his example, but in Obj-C, this will blow up, if a 0 is passed to it.

- (NSInteger)fractionWithNumerator:(NSInteger)num divisor:(NSInteger)divisor {
    return num/divisor;  

We normally think to add:

assert(divisor != 0)

But he argues that instead either the types should be modified so that there is no such thing as an input that would blow up the function. In Swift, he created a new optional type, called Real, and defined it so that it is nil if it is 0, which moves the failing earlier in the code.

Thinking about Objective-C, the only way that I could see to do this would be to use an NSNumber, and create a subclass of that, which conformed to the Real characteristics. Then, of course, be careful with nil checking.

Anyway, I really like this paradigm for thinking about functions.


Now read this

CSV to Multi-Markdown Tables

One person noticed yesterday’s yak-shaving and liked it, which was all the excuse I needed to shave it some more. But I am good to go for now, though this still is still fairly fragile: you have to select only the table lines, there’s no... Continue →