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

Logging into a website with Powershell

Powershell is great, and it's lately been my go-to shell while I'm working on Windows. Sorry command prompt I really don't do a lot of work in the shell, but I do like to play with low-level interfaces from time to time. The article is about Linux shells, but goes into good explanation about what a shell is if you don't know. Log into a website Today, I wanted to do something that I have never really tried before and that is logging into a website using Powershell . The concepts behind this are quite simple really, as Powershell has support to send HTTP requests  and that's usually all we need, unless the server has CSRF protections in place (which it should). We are going to attempt  to log in to my favorite website for buying socks, Absolute Socks : Is that a turkey?! In order to do that, we need to have a login. So if you don't already have an account on www.absolutesocks.com , go make one now. Viewing the login request On websites,