I think I get it
Thursday, August 27th, 2009
‘It’ being object oriented programming (OOP).
For a long time I got frustrated with reading tutorials telling you about inheritance and other useful features of using OOP’s class-based approach. The trouble is that in the example scenarios given (eg a ‘bird’ class which inherits from an ‘animal’ class) the set theory-like approach to writing code to represent things makes sense. But when it comes to building a website or something similar, and creating classes which do not display a nested structure, the analogy with set theory falls away and largely (at least in the websites I’ve worked on) you’re left with a convoluted structure which, at first glance, could just be done away with in favour of using normal variables and functions instead of properties and methods. I could see how perhaps the stronger structure might help organise code, and was gradually getting mor ecomfortable with the techniques, but still didn’t really get why using OOP was so important.
But now I think I do, courtesy of wikipedia, which has the best summary of the motivation behind OOP I’ve ever read:
The methodology focuses on data rather than processes, with programs composed of self-sufficient modules (objects) each containing all the information needed to manipulate its own data structure. This is in contrast to the existing modular programming which had been dominant for many years that focused on the function of a module, rather than specifically the data, but equally provided for code reuse, and self-sufficient reusable units of programming logic, enabling collaboration through the use of linked modules (subroutines). This more conventional approach, which still persists, tends to consider data and behavior separately.
After reading this it’s all become clear to me what the point is – creating a more concrete connection between a thing and what can be done to it. In a real world situation I would liken it to having the steering wheel in the car, always ready to be used to steer the car, as opposed to having a steering wheel which can be passed around and maybe tried on other things, eg a chicken, a whale, a front-bench tory… where the results would be unpredictable (apart from the tory, who would almost certainly find the experience arousing). And as long as you define the steering wheel at a high enough level (eg the ‘vehicle’ class has a steering wheel, which the ‘car’ class inherits) you don’t fall foul of code duplication either.
