Webpop

Sharpening the OOP Axe

I spent quite a lot of the last two weeks completely rewriting the internals of a PHP based web-service in use at webpop.com.

The codebase was seemingly coded in an object oriented style taking advantage of the new class system of PHP5, but in reality all connection between objects was based on inheritance, meaning that in practice it was all one humongous class containing all the functions of a procedural program.

I wanted to turn this into a cleanly architectured application with small objects, each doing relatively little, but simply couldn’t find a way to evolve the huge inheritance blob of classes into something like that through small and gentle, gradual refactorings; so I decided more drastic steps was needed, and began a complete rewrite.

One beautiful characteristic of rewrites, is that they present us programmers with pretty much the only case of having a full specification that actually specifies what the customer wants in the end. My spec was an API specification of 26 methods for a REST based web-service, and I had a set of acceptance tests in place to make sure that those 26 method calls worked as expected.

With this foundation in place I carefully started building up a new architecture taking advantage of PHP5’s reworked OOP features, and with no over-abuse of inheritance. During the first week I implemented no more than 3 of the original 26 methods, and yet I confidently told my bass that I expected to finish the rewriting before the end of the second week. I avoided the question of how many of the methods I had gotten done so far, when asked, because I knew the number would be wildly misleading.

This was not due to wild optimism or pure insanity, but because of how OOP works and feels when it’s done right. What I did, while implementing those 3 methods, was extracting the basic generic building blocks of the web-service’s operations. Abraham Lincoln is supposed to have said once “If I had eight hours to chop down a tree, I’d spend six sharpening my axe.” While taking my time, carefully implementing those 3 small method calls, I was sharpening my virtual and object oriented axe.

When the second week started, I had basically all my small building block in place, and 3 days into the week I was done implementing all the remaining 23 methods – it was simply a question of putting existing blocks together in the right way. This is, to me, what OOP is all about: building small reusable blocks with enough flexibility that adding new functionality feels somewhat like a playing with LEGOs.

At the end of the two weeks the rewritten service passed all the acceptance tests, with a line-count around a fourth of the original code-base and with a far more flexible architecture, that has already made me implement several feature enhancements that would have been seriously big pains to add before the rewrite.