Don’t get me wrong, I’ve been familiar with the principles of OOP for a while, through initial forays into the world of Java as well as working briefly on ASP.NET projects. I’ve read so many times those simplistic examples of inheritance, where a Dog is a subclass of an Animal and a Car is a subclass of a Vehicle, and it all seems logical enough.
All these nicely defined object oriented principles seemed to be irrelevant, however, when I decided to apply them to a pet project of mine at work: the rewrite of the collection of NHS Wales’s generic sites.
I thought that using OOP in a language I’m familiar with, ColdFusion, would help to consolidate my knowledge, but thanks to my ad hoc way of working, and hampered by my procedural programming habits, the code soon turned into a weird mess of interrelated connections. Objects were passed back and forth willy-nilly and copies of the same variable were being stored in a number of scopes and objects.
It just didn’t “feel” right. It may be strange for the non-programmer to talk of “elegant”, or “ugly” code, but ugly is what grew in front of me as I tapped away at the keyboard. What’s more, I was beginning to think that a simple website, delivering one database-driven page at a time, wasn’t really a prime candidate for the object oriented approach. Hello Mr Sledgehammer, meet Mr Nut.
I’d originally built a Page object, which generates and stores the constituent elements of a page (the navigation, search box, sidebars and the like) for later rendering. The Page object also invoked a component in a cfc somewhere to build the main content of a page. The component depended on the page type - a news item would get content from news.cfc, a sitemap from sitemap.cfc, and so on. However, to access the methods and properties of the Page object, I needed to pass the entire Page object as an argument to the component - pretty nasty!
Then, an epiphany. A news item is a particular type of page. So is a sitemap. It’s inheritance! I knew all about it, I’ve read about it so many times, why didn’t it occur to me before that I should use it? A NewsPage is a subclass of a Page in exactly the same way as a Dog is a subclass of an Animal. A short time rewriting made everything more elegant.
For me, then, it was all very well learning about OOP but it’s hard to shake the habits of procedural programming. I knew about it, but didn’t quite “get” how to apply it. That knowledge begins to coalesce with practical experience, like trying the pieces of a jigsaw in various configurations before they start to fit.
I can now even see how interfaces, another initial stumbling block for me, can be useful in ensuring that new page types conform to a certain set of standards. It’s a strange feeling - finally it all makes some kind of sense.