Friday, September 21, 2007

Types as automated tests of your design

Apparently, I praised the concept of blessed interface.

No, I'm not. I'm just saying that if you rely on an interface, then explicitly define that interface instead of letting it magically appear from your coding. No, you should not predefine your interface and stick to it whatever the cost. Yes, during the development phase, the interface will evolve until it contains what you need.

But when this is done, you have defined an expected behavior. You have successfully built an abstraction. Congratulations.

Now, imagine you have trouble defining that abstraction, because you keep adding to it, or you can't possibly find a way to express what you want. Congratulations again. You have found a flaw. Do you think you've found a flaw in the concept of static typing? Think again. You have probably found a flaw in the way you try to model the problem space. You are probably writing code that is expecting too much of the object it receives.

One guy complained that once he created the concept of Ball and added a radius to it, there was no easy way of defining a rugby ball, because it was not spherical, and thus radius had no meaning. He - of course :-) - blamed static typing for his own mistake of making all balls in the world round.

Static typing requires you to think in order to find appropriate abstractions. If you can't find them, or need them to change constantly, you have an incomplete - or plain wrong - idea of the reality you try to model. Types allow you to test your design against reality. Yes, your design will be better if you use properly designed interfaces, it will relate to problem space. Yes, it is worth the cost, because this interface is no less than an automated test against your comprehension of the problem.

No comments: