Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deeply Nested Inheritance - Bad or Good Practice?

I am in the process of making a PHP web application. I have a situation that I believe would foster a good time for nested inheritance. Anyway, here is my situation:

public class RecurringWeeklyEvent extends RecurringEvent { }

public class RecurringEvent extends Event { }

It does not seem to me that this would be a bad design practice; however, I am not an advanced Object-Oriented programmer by any means. With that said, before I venture off using this kind of code in my application, I would like to know if this is a good or bad practice from more experienced/qualified programmers.

NOTE: I changed the title from multiple inheritance to nested inheritance after being corrected of using the wrong term.

Thanks

Steve

like image 967
Stephen Watkins Avatar asked Apr 23 '26 13:04

Stephen Watkins


2 Answers

To quote David West:

The definition of inheritance then becomes, "A superordinate-subordinate relationship between classes in which the subordinate (child) has the same behaviours (responsibilities) as the superordinate (parent) plus at least one additional."

So what you're doing seems fine, so long as you're adding behaviour to your derived classes (i.e., inheritance is not a tool for adding in extra members), and (preferably) not altering the defined behaviour of the bases classes.

Elaboration

What duffymo says is correct. I want to add my 2p from my interpretation of what David West says in his book.

Overriding methods should be avoided where possible. Changing the behaviour of a method in a child class could lead to confusion for implementers.

(I'm still getting my head around OOP and Object Thinking.)

like image 102
Matt Ellen Avatar answered Apr 25 '26 02:04

Matt Ellen


The best way, would be to have the RecurringEvent, and each object has information on when it recurs, probably every n days (or even hours, minutes).

From these two lines, I'm guessing you're making a calendar? You will probably want to make a different class (sub class of recurring event) for events that recur in non standard ways (for example, third monday of the week, first monday in October, and the like).

And just so you know, this isn't multiple inheritance, multiple inheritance is when a single class has more than one direct parent class. In this case, RecurringWeeklyEvent extends RecurringEvent which extends Event. With multiple inheritance, it would be RecurrungWeeklyEvent extends RecurringEvent and Event (I'm not sure the syntax to do this in php or java).

like image 43
Jeffrey Aylesworth Avatar answered Apr 25 '26 03:04

Jeffrey Aylesworth