Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 980
Paulo Ricca Avatar asked May 27 '11 00:05

Paulo Ricca


1 Answers

Inheritance ('extending classes') imposes significant limitations on class design and I'm not sure the use of interfaces as a replacement for inheritance is the best idea since it fails the DRY test.

These days, Composition is favored over Inheritance, so you might consider this post: Prefer composition over inheritance?

like image 143
Rob Raisch Avatar answered Nov 01 '22 13:11

Rob Raisch