Tuesday, November 09, 2004

I think I finally get it.

I think I might have had a bit of a revelation yesterday on the way home from work.

Walking along, rain blowing in my face, bit of Metallica on my MP3 player (And yes, Metallica, I did pay for it!), deciding whether to get the carbonara sauce out of the freezer or get the chicken out for tea, and suddenly I saw a light. I don't know if it's the light, but it was certainly bright! This, by the way, has nothing to do with inheritance. Luckily, being cold, damp. tired, hungry and annoyed (the tube was delayed as well!) is not an analogy for inheritance.

I think I finally get it.

I was thinking about a general object 'Item' that you might get in a shop or catalogue. Now up until now, I would have put together a big old class that encommpassed all my functionality, including ordering, (Item.AddToOrder()), Catalogue information (Item.Image) and so on.

In the past, I would have done one of two things:

1) Had a great big IItem interface, and had to implement a whole shedload of dummy methods to make it compile

2) Implement a few extra classes, for orders and so on which contain within them a property 'BaseItem' which returns an item

1's a bit clumsy, and means writing a whole load of unneccesary code.

2 is a little better, but still means writing a whole load of extra code. I mean, to get to it, you're looking at a minimun 3 extra keystrokes to get to a property of the BaseItem ('B', then tab to autocomplete it, then a '.'). Not ideal.

Inheritance is the key. I can create an 'Item' class, implement methods and properteis for the bits that are universal and then create inherited CatalogItem classes, OrderItem classes and so on that expand on that.

Now this isn't anything new or revolutionary. I've just re-read this post and thought to myself 'Yeah. I already knew that. What's the big deal?'

The big deal is this: Although I knew it already. I could probably have even explained it to someone else at a push, and I certainly know what people are on about when they talk about it, I didn't really get it.

Does this happen to anyone else? I mean I've used inheritance in the past, I've expanded or customised frmaework classes to make it work exactly how I want it, I've even fixed bugs shortcomings in my own code using inheritance.

Only now, though, do I think I actually really get it. I might even go as far as to say I understand it.

Just wanted to share.

No comments: