The deep, the shallow and the ugly (classes)

Previously I showed parts of the API of my new module Graphics::Toolkit::Color. This time I want to mention some bits about the code base, which demonstrate what I tried to say long ago (sorry for the long delay i hope I can complete the series).

From technical point I was willingly cutting some corners - but what I want to talk about is the software engineering angle of good code.

I recently posted on twitter a talk by TCL designer Ousterhout where he explains good designed classes are deep. By that he means the API to the user contains the least possible amount of complexity (is simple - needs very few bits of knowledge). It should hide as much complexity as possible. As a consequence he argues against the notion of small classes and small methods. But I think there is a misunderstanding. Small classes and small methods are about code clarity and maintainability. And you wan to have both clarity and complexity hiding. And I believe both are not different values you have to compromise between but sides of the same coin. There both result of a) finding right abstraction and b) keeping the most information in that layer or file. Many confuse that with encapsulation or other concepts sold as OO but they apply to subs and packages as well. If you are in a certain code file you have all the details, the implementation the comments the signatures (API) all you need to understand the picture. If not the code has serious design flaws. And if you zoom out (being in other, calling part of code base) names of classes, sub and args should reveal enough information to clarify what are you doing with what tools.

Coming back to John Ousterhout: if each command hides implementation details, several of them together in one subroutine contain enough complexity that deserves its own name. Do not forget that to outside world you only expose a few method that can already call several subs of same file or layer. Thus you get a deep class (which does serious chunks of work) and its readable.

Graphics::Toolkit::Color are in reality 3 modules. One is handling the low level operations, value like range checking, value conversion, averaging and so on. This is about single or few numbers and it does not have to be object oriented. Another module is handling the color names. I mean even the list of constants is so long it should not be intermingled with too much other code of the file gets hard to navigate. That is why the class sitting on top both packages can be rather concise and yet is handling a lot of complexity.

I know to some of you this all is like explaining how to use the bathroom. But i think its worth to explicitly thinking about to write code we enjoy to work with even next year. And it's also about to get the theory straight behind what we are doing and not get fooled by by buzz words.

Leave a comment

About lichtkind

user-pic Kephra, Articles, Books, Perl, Programming