Skip to main content

Do you choose inheritance or interfaces?

What's the right answer?

It depends (credit to https://www.pinterest.it/bjgreenberg/)
The answer to every programming question

Let's explore both options and when you might choose to prefer one or the other. Pay extra special attention and focus because this is a common job question and an answer you should fundamentally know if you want to become a better software developer!

Why choose interfaces?

Choose inheritance when your objects have a has-a or can-do relationship. What does this mean? A has-a relationship means the object implementing the interface "has a" object/thing that is the interface. Here is a concrete example of a has-a relationship:
public interface IWheel
{
    public void TurnRight();
    public void TurnLeft();
}

public class Boat : IWheel
{
    public void TurnRight()
    {
        // implementation
    }

    public void TurnLeft()
    {
        // implementation
    }
}
A boat has a wheel, and is an example of using an interface with a has-a relationship.

A similar example can explain the can-do relationship:
public interface IDisposable
{
    public void Dispose();
}

public class ExpensiveObject : IDisposable
{
    public void Dispose()
    {
        // implementation
    }
}
In a can-do relationship, the object implementing the interface can do the operations that represent the interface. The most common example I've seen is with the IDisposable interface. The ExpensiveObject can be disposed.

The IDisposable interface is heavily used in C# programming and its recommend that you read up what the best practices are when using objects that implement the IDisposable interface.


Why choose inheritance?

Choose inheritance when your objects have an is-a relationship. An is-a relationship is when your object is directly related to the base class. Here are two examples:
public class Human
{

}

public class Employee : Human
{

}

public class Father : Human
{
    
}
An employee is a human. A father is a human.

Another reason why you might choose inheritance over interfaces is when you need to share common properties. Here is an example of that:
public class Shape
{
    public double Area { get; set; }
}

public class Triangle : Shape
{
    // Has access to Area
}

public class Circle : Shape
{
    // Has access to Area
}
Both the Triangle and Circle need an area property, and by using inheritance we are able to ensure that both Triangle and Circle have that property. This is polymorphism at work.

Building off our previous example, we would also opt to choose inheritance over interfaces when we need our child classes to share the same signature but implementation would differ. An example below is where we need to find the areas of a Triangle and Circle:
public class Shape
{
    public double GetArea();
}

public class Triangle : Shape
{
    public override double GetArea()
    {
        // return (b * h) / 2
    }
}

public class Circle : Shape
{
    public override double GetArea()
    {
        // return pi * r^2
    }
}
We use the override keyword to change the method signature in both the Triangle and Circle classes.

La fin

Use inheritance when you can share methods/fields/properties of the base class with derived or child types and the relationships between classes represents an is-a relationship. Use interfaces if you do not need to share methods/fields/properties between the base class and derived classes or the relationship between classes represents an has-a or can-do relationship. 

Decision table of when to use interfaces or inheritance
A decision table

*- In C# 8, interfaces are going to get the ability to add base implementations within the interface. While this might lead you to assume interfaces will take over some of the responsibility that inheritance can provide, this change was/is being made for a different purpose. 

Allowing interfaces to implement base behavior allows users/maintainers of public interfaces to add new members without breaking existing code that implements the interface. Don't code the way it wasn't intended to be coded.

Comments

  1. i am ERIC BRUNT by name. Greetings to every one that is reading this testimony. I have been rejected by my wife after three(3) years of marriage just because another Man had a spell on her and she left me and the kid to suffer. one day when i was reading through the web, i saw a post on how this spell caster on this address AKHERETEMPLE@gmail.com have help a woman to get back her husband and i gave him a reply to his address and he told me that a man had a spell on my wife and he told me that he will help me and after 3 days that i will have my wife back. i believed him and today i am glad to let you all know that this spell caster have the power to bring lovers back. because i am now happy with my wife. Thanks for helping me Dr Akhere contact him on email: AKHERETEMPLE@gmail.com
    or
    call/whatsapp:+2349057261346










    i am ERIC BRUNT by name. Greetings to every one that is reading this testimony. I have been rejected by my wife after three(3) years of marriage just because another Man had a spell on her and she left me and the kid to suffer. one day when i was reading through the web, i saw a post on how this spell caster on this address AKHERETEMPLE@gmail.com have help a woman to get back her husband and i gave him a reply to his address and he told me that a man had a spell on my wife and he told me that he will help me and after 3 days that i will have my wife back. i believed him and today i am glad to let you all know that this spell caster have the power to bring lovers back. because i am now happy with my wife. Thanks for helping me Dr Akhere contact him on email: AKHERETEMPLE@gmail.com
    or
    call/whatsapp:+2349057261346










    ReplyDelete

Post a Comment

Popular posts from this blog

UI redesigns are mostly a waste of time

To preface the article, I primarily work on, and prefer, back-end code. I've been involved in both web and software development for over 4 years now and worked with many front-end and back-end frameworks. New Twitter UI Before all of the UI designers that read this go out and riot and champion against me for saying UI redesigns are a waste of time, let me say that I do value design . I think at the bare minimum, a product or website needs to be usable , and if you possess a good eye and steady hand , you should feel compelled to create something that looks pleasing. David Just stop redesigning the UI all the time . UI redesigns, in my opinion, are a waste of time 95% of the time. Let me explain further. No one cares Come see our fresh new look ! What about our new  material design , come see! I'm sorry, but besides fixing the UI where it impacts the usability of your application, no one is raving about how a redesign makes the application any better. ...

[Fix] - ASUS PCE-AC68 adapter (no internet)

There seem to be a lot of problems with this adapter, even with such strong performance . Why so many issues? I'm not quite sure, but I needed to find a fix because I kept on losing wifi. The ASUS PCE-AC68 The fix Keeping it short - this is how I fixed the issue: Downloaded the driver for my OS from ASUS's support page -  https://www.asus.com/us/Networking/PCEAC68/HelpDesk_Download/ (in my case it was Windows 10 64-bit). Open Device Manager by holding the Windows key and pressing R, then typing "devmgmt.msc" and hitting Enter. (Don't worry, this isn't a scam . We are simply opening Window's Device Manager through the Microsoft Management Console snap-in .) Navigate to the yellow warning sign sitting under Network adapters and right click it. Select Update driver . Select Browse my computer for driver software  and choose the following path of the OS that you have installed on your computer. (The path for the driver on my computer was C...

How to block online ads with the hosts file

Am I the only one who is skeptical clicking on ads I see online? Yes, I know it is the lifeblood of entrepreneurs , but I really don't care to view more than I have to. We all know the 7 +- 2 rule ; we have a limit of the amount of information we can take in at a single time. It's a fact. We are not infinite in our abilities alone - let's just let the computers do the thinking for us .   Inline Adsense ads While I recently tried to set up a more elegant solution, I wanted to share with you how you have the power to block ads (in case you didn't know already) and regain [more] control of what you are looking at online. Extensions This is the easy answer, just install Adblock Plus ( Chrome ). Adblock Plus on the Chrome web store Adblock does it all for you. Ads? No more. It's really a golden bullet. However, if you want to grow as a developer, sometimes it pays to try and do things in a different way in order to learn how more things work und...