Tuesday, June 26, 2007

Objects are too small

I was thinking this morning about parsing, and was contemplating the methods I wanted to add on objects in the parser. What I quickly realized that it wasn't adequate to just have a "parse()" method, because there is context associated with the parse itself. So I added an argument to the parse method to allow passing of a context for the parse--and I realized a flaw of object-oriented programming.

Many operations that we code require more than just a receiver and method call: there's often at least 1 other object involved that is not an argument.

And that's one of the reasons why object-orientation has it's limits, and why C++ has it's limits. A good language allows common patterns to become automatic. Adding a context parameter to every parse method is not automatic, but is an example of the tedium that programmers must go through to express their ideas.

So maybe I don't need a context, you say? Make the context a member of the object itself, and just let the object encapsulate it. Great, now I have to add the context to every constructor so that references propagate through my hierarchy as parent nodes create child nodes. Don't add it to the constructor? Okay, now I either have to overload the new operator, or restrict my code to using factory functions--likely still using the context in a private constructor.

So, the point is, many operations in code require more than a single target, a method selector, and a set of arguments. Since most code for hard problems does require context to perform an operation, incorporating that context should be made automatic. Every time you correctly save time for the programmer, you've prevented a thousand bugs.