Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance or identifier

Does anyone here have opinions about when to user inheritance and when to use an identifier instead?

Inheritance example:

class Animal 
{
    public int Name { get; set; }
}

class Dog : Animal {}

class Cat : Animal {}

Identifier example:

class Animal 
{
    public int Name { get; set; }

    public AnimalType { get; set; }
}

In what situations should i prefer which solution and what are the pros and cons for them?

/Lina

like image 563
Lina Avatar asked Mar 16 '10 09:03

Lina


3 Answers

It depends on the type of the actions you need to be done in your system. For example if you have some common action that should be done in the different way for each of your objects than you should use inheritance, e.g.:

class Shape 
{
    public abstract void Draw();
}

class Circle : Shape 
{
    public override void Draw()
    { 
        /* Custom implementation for Circle. */
    }
}

class Box : Shape 
{
    public override void Draw()
    { 
        /* Custom implementation for Box. */
    }
}

On the other hand if some type of and object more looks like its property you should use what you called as "identifier":

enum Color
{
    Red,
    Green,
    Blue
}

class Box
{
    public Color BoxColor { get; set; }
}

You can use inheritance here (but it doesn't look so good): RedBox, BlueBox, etc. The difference is that all boxes (even ones with different color) would be handled in the same way and their behavior will be common.

like image 141
Andrew Bezzub Avatar answered Oct 19 '22 21:10

Andrew Bezzub


What you call an "identifier" I would call an enum approach.

Using an enum to sub-divide is only suitable to distinguish a small, fixed set of possibilities. When you over-extend it you will see switch statements appearing everywhere in your code and that is a strong indicator you should use inheritance instead.

like image 4
Henk Holterman Avatar answered Oct 19 '22 22:10

Henk Holterman


  • If the only difference between animals is their type, use the AnimalType property.

  • If different animals have different implementations of properties and methods or additional ones, create classes that derive from Animal.

    If checking for the type of animal is a common use case, consider providing a AnimalType property as well, as an alternative to lots of is/as.

like image 3
dtb Avatar answered Oct 19 '22 21:10

dtb