Search code examples
oopinheritancearchitectureinterfaceextend

How to move away from Inheritance


I've searched in here and other forums and couldn't find a good answer.. I kind of know that Extending classes isn't the best of practices. And that I should use Interfaces more. my problem is that usually I start creating Interfaces and then move to Abstract classes because there's always some functionality that I want implemented on a super class so that I don't have to replicate it in every child classes. For instance, I have a Vehicle class and the Car and Bike child classes. a lot of functionality could be implemented on the Vehicle class, such as Move() and Stop(), so what would be the best practice to keep the architecture clean, avoid code repetition and use Interfaces instead of Inheritance? Thanks a lot!

(if you have no idea why I'm asking this you may read this interesting article: http://www.javaworld.com/javaworld/jw-08-2003/jw-0801-toolbox.html)


Solution

  • Agree with tofutim - in your current example, move and stop on Vehicle is reasonable.

    Having read the article - I think it's using powerful language to push a point... remember - inheritance is a tool to help get a job done.

    But if we go with the assumption that for whatever reasons you can't / won't use the tool in this case, you can start by breaking it down into small interfaces with helper objects and/or visitors...

    For example - Vehicle types include submarine, boat, plane, car and bike. You could break it down into interfaces... IMoveable + Forward() + Backward() + Left() + Right()

    IFloatable + Dock()

    ISink() + BlowAir()

    IFly() + Takeoff() + Land()

    And then your classes can aggregate the plethora of interfaces you've just defined.

    The problem is though that you may end up duplicating some code in the car / bike class for IMoveable.Left() and IMoveable.Right(). You could factor this into a helper method and aggregate the helper... but if you follow it to its logical conclusion, you would still end up refactoring many things back into base classes.

    Inheritance and Aggregation are tools... neither of which are "evil".

    Hope that helps.