Home > Uncategorized > misuse / stupid use of inheritance

misuse / stupid use of inheritance

Here we will see how inheritance can lead to stupid design . Following code may not run coz i like to show you the concept not the coding.

We will have two class.
1)TwoDBox Class
2)ThreeDBox Class.

Synopsis of this post is ThreeDBox should not inherit TwoDBox but it may use TwoDBox.


class TwoDBox{
$var length;
$var width;

function constructor ( $len, $wid ) {
$this->length = $len;
$this->width = $wid;
}

function getArea(){
return $this->length * $this->width;
}

function getPerimeter (){
return $this->length + $this->width;
}

function getDiagonal () { //lets assume the box is square / rectangular

return sqrt($this->length*$this->length + $this->width * $this->width);
}

}

Class ThreeDBox extends TwoDBox {

var $height;

function constructor ( $len, $wid, $height ){

$this->width = $wid;
$this->len = $len;
$this->height = $height;
}

function getVolume(){
return $this->width * $this->len * $this->height;
}

}

This program is quite ok , it is using inheritance to save some code duplication.

But is that good use of OOP?
Here in the class ThreeDBox we have some unwanted function came from TwoDBox which bear meaning in twoDbox but not relevant in ThreeDBox like ( getArea, getPerimeter,getDiagonal).

So, when one has a class diagram of this ThreeDBox (s)he may get confused what this function means in the context of this ThreeDBox class.

But if the functions of TwoDBox are meaningful in ThreeDBox or they are overloaded in ThreeDBox then it is quite ok.

But here come the solution to do it in right way or at least better way( according to my mind ).
We just need to Rewrite the ThreeDBox class.

Class ThreeDBox {

var $twoDBox;
var $height;

function constructor( $length,$width,$height){
$twoDBox = new TwoDBox($length,$width);
$this->height = $height;
}

function getVolume(){
$this->twoDBox->getArea() * $this->height;
}
}

Does this make sense ?
Here in ThreeDBox we have no extra unrelevent methods ( as before like getArea(), getPerimeter(),getDiagonal() ) not pertinent to this class.

So, clean code, and no misuse of power 🙂

The concept is borrowed from OOA&D by HeadFirst.

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: