Author Topic: Overriding functions in a child object vs. extending parent object code  (Read 2184 times)

Offline AskMeLater

  • Acquaintance
  • *
  • Posts: 8
    • View Profile
I'm new to muds, LPC and coding.  I was wondering what the feeling is about overriding functions in a child object vs. extending the parent code.  Is the decision mostly based on is this new functionality specific to this one object or could be used by many similar objects?  Also, is it considered good form when overriding a parent function to call the parents function if you are just extending functionality?  Like all you are doing is adding something, but you want all the parents code to be run as well.  So you use <parent>::SomeFunc() to call the parents function before or after your modifications.

As an example I'll explain what I'm working on.  I have a book that I want only players over a certain level to be able to read.  In the code for this specific book I overrode the GetRead function from /lib/events/read.c (which is ineherited by item then book).  The code works like I want.  If you are not higher than a certain level you cannot read the book.  Anyway, I call book::GetRead() and it seems to work like expected.  I'm just curious what the best practices are for this kind of thing.

Thanks,

Offline Sluggy

  • Friend
  • **
  • Posts: 91
    • View Profile
    • Stellarmass
Re: Overriding functions in a child object vs. extending parent object code
« Reply #1 on: December 26, 2008, 07:15:40 pm »
The whole idea of inheritance is that you want different objects to share some common functionality or at the very least, a common interface. It makes sense then that if one object needs to do more or do something different than the rest that you will have to override this function. It would be silly to hardcode all of this in the base object and have to add extra logic to check for special cases that may never occur.

So yes, to answer your question, if you want a specific book to do a specific task that is different from every other book when using the same functionality (e.g. reading it) then you should override the default function to replace or extend as you see fit.

As I said above, it seems overkill to modify the base class to do this extra work if it will never even happen in most cases, plus it means you risk breaking all existing code based on it. If this is common feature that *all* books should have it would almost certainly be better to just make a new object inherit the base and then inherit all future books from that. This goes along with the open/close principle: objects should be open to extension and closed to modification.

hth
« Last Edit: December 26, 2008, 07:17:14 pm by Sluggy »