Saturday, April 30, 2005

Distinctions and ifTrue:/ifFalse:

It is said that the purpose of proper coding should be the elimination of all sends of ifTrue:/ifFalse:. Besides the exaggeration, there's a lot of truth to this.

First of all, a decent lack of ifTrue:/ifFalse: means that most message sends are meaningful in the context of the receiver.

Stop here and consider: why would you want to send a message that is not meaningful in the context of the receiver? Why would it be necessary for senders to first check if the message makes sense or something like that? More profoundly:

Why are you, the developer, adding foreign ifTrue:/ifFalse: to message chains that should make sense to themselves? Maybe because the code isn't that great?

From a more practical point of view, let's say you eliminate ifTrue:/ifFalse: because you add a subclass that redefines some behavior so the message send always makes sense.

You just optimized the code.

Because now, the VM is taking advantage of all its extraordinary power to extract performance out of thin air. There is no ifTrue:/ifFalse:, the message send becomes polymorphic, and polymorphic inline caches are in your VM exactly for the purpose of making these sends to go really fast.

In short, you eliminated the check that comes before ifTrue:/ifFalse:, you also got rid of ifTrue:/ifFalse:, and you replaced that with a polymorphic inline cache in a VM that could be doing JIT stuff.

There's no way to beat that kind of performance boost. Plus it gives you the ability to give the new class an intention revealing name.

Remember, distinctions are the consequence of intention. Different intentions lead to different distinctions. Remember McGyver? Your intentions were different than his, so you distinguished things different.

Sometimes it doesn't work that well though. For instance, Integer>>isPrime is a total pain. Imagine the mess the PrimeInteger class would create.

Before I wrote this, I couldn't put my finger on exactly why this was. I thought it was because it was a distinction that was not cost effective for the developer to make.

Now I think I see it much better. It's because in general terms it's not a distinction you can make before messages are sent.

Think of the implications of accepting that messaging can distinguish... just like we do...

No comments: