Why you should NEVER use inheritence in your PHP OOP Code!

April 9, 2014

franken-software
Hi!

First all of, I have to say that I love this guy on the right!!

🙂

Anyone who knows object oriented programming is probably having kittens now! How can a nerd like Stef be dissing one of the fundamental tools in our OOP toolbox? Isn’t inheritance one of the key tools that makes code reuse possible?

Well, only in the case of foundation code. Very few of use write that kind code. Most of us are writing business objects and business objects should be using interfaces and object composition.

What is foundation code?

Think the core of web servers, the core engines in database servers. All the stuff that is pretty much written.

Share object code as complete objects, leave the code alone!

Code Reuse doesn’t come so much from reusing code found in one class and using inheritance to bring it into another. No, it’s more about reusing objects across projects and reusing COMPLETE objects within the same project.

Composition over Inheritance

Favor combining objects (this is called composition) rather than creating new objects that inherent functionality from parent classes. Why?

Because inheritance creates fragile dependencies – if some nerd comes a long and decides to rewrite some of your base classes – you will be screwed! I’ve seen it firsthand. It’s not a pretty site: nerds screaming and yelling, app functionality breaking in 10 different places … nerds throwing wussy punches with the intent to do damage.

.. But since they are nerds, no one really gets hurt.

With composition, your objects are loosely bound. That means it’s easy to swap objects in an out of your code base, since your objects are not dependent on the INTERNALS of another object – something you get (unfortunately) with inheritance.

Keep your objects small, highly focused and dumb.

Objects should have very specific task and they should be dumb to what’s going on around them.

Objects should take in an input and spit out a generic output. You don’t want the behavior of your objects to be easily influenced by outside forces. If you want to modify what an object does for you, just grab the output from said object and modify the OUTPUT with another objects methods.

… Keeps the objects dumb I says!

Stefan Mischook
killerPHP.com

Comments

Comments are closed.

To Top