OO as roadmap

rats on 2005-03-09T04:20:45

I remember a comment Bertrand Meyer made in OOSC2 that OO design simply provides an orderly way of arranging all the bits and pieces of a program that get scattered all over the place in traditional/procedural programming. OOD gives a roadmap of where to find things.

A refactoring exercise yesterday is a classic example. The existing code seemed to be written by someone who was reluctant to use anything more complex than single index arrays and single key hashes to store the quite complex data being retrieved from the database. I replaced the single keys/indexes with equivalent [array]{hash}[array]{hash} structures. But then it became obvious I really needed to replace the structures with objects. The clincher was a 50-line sort routine which used splice()!! All the sort was doing was separating the jobs into today's and yesterday's and then sorting the two lists from latest to earliest but because of the tangled up structures it was really difficult to do this using 'sort grep @array'.

I created a Job class and then the sort reduced to two lines: one to select and sort the previous day's jobs; one to select and sort the current day's jobs. I then noticed six lines of code at the end of the old sort routine which calculated column breaks for displaying the jobs (and held the results in global variables!). Why were they there? Well I supposed they had to be somewhere and the sort routine was as good a place as any. Turns out the lines and global variables weren't even needed but you wouldn't realise this until the sort routine shrunk so dramatically.

I occasionally hear or read dismissive comments about OO. "I can write faster code using paradigm X or paradigm Y" sort of thing. But I use OO as a tool to help me order and arrange my thoughts. Thinking is hard and I'll use any help I can get. If, as a side-effect, I can reduce a 50-line chunk of code to 2 lines, well that's nice too.