Skip to main content

Abstract Classes and Interfaces

[PLACEHOLDER]
Author: Carlos G.

Sometimes you are working on a project, perhaps finding and fixing a bug, and you can see all the “jumps” the debugger does to actually find the issue.

When I mean “jumps” I’m referring to the way that goes from 1 class to another one, or to an abstract class or to an interface… and by that time you say – “why the hell they used all this for such a simple functionality!”

But, when the frustration is all gone I bet you realize the good job that some of these developers have done, because things are there for a reason…sometimes the reason is “I’m just learning new concepts and I used this simple project to apply them and mess with everyone’s mind”… but other times is quite the opposite and they come up with a well, structure and easy code to maintain.

So, to the point: should we use abstract classes or interfaces and when?

I’m going to try to answer that as simple as possible and at the end you would find references to a lot of good guys that have been answering that in their own blogs or via stackoverflow, presenting good examples. First let’s start with some definitions:

Definitions and Example:

Abstract class: they are base classes that cannot be instantiated. Other classes can derive from them.

Note: a class can derive from an abstract class and also implement interfaces. You can only inherit from one abstract per class. To my knowledge C++ is an exception to that rule.

Here is simple example, using C#:
I’m creating a nonsense abstract class with 1 method called hello. Then I’ll have a class that will implement this one. The intention is that in a webpage or a view, you will use it to print the word “hello”.

The abstract class:
namespace testing.classes.abstracts
{
    public abstract class baseClass
    {
       public string hello()
       {
           return "hello";
       }
    }
}

The class:
using testing.classes.abstracts;
namespace testing.classes
{
    public class childClass: baseClass
    {
    }
}
The implementation:
public partial class page : System.Web.UI.Page
    {
       protected void Page_Load(object sender, EventArgs e)
       {
           var child = new childClass();
           Response.Write(child.hello());
       }
    }


Interfaces: it is like an abstract type that contains nothing really but exposes methods. Then unrelated classes can actually implement the interfaces, this can potentially reduce dependencies and/or make the code reusable.

One of things that interface help is because it provides some standard, boundaries if you will.

Picture the scenario where you have you 2 teams of developers in different cities, working together on a project but on different pieces. As long as both teams are using the proper interfaces for the things that require working together then, in theory, things should go ok, no matter if one developer is all formal in he/she style and the other is more “yippee ki-yay mother…”

Here is another simple nonsense example using C#:

The interface:
namespace testing.interfaces
{
    public interface interface1
    {
        string givemeText(string text);
    }
}

Then I update the original class:

using testing.classes.abstracts;
using testing.interfaces;
namespace testing.classes
{
    public class childClass: baseClass, interface1
    {
    }
}

We compiled and BUM!!!! An error:

'testing.classes.childClass' does not implement interface member 'testing.interfaces.interface1.givemeText(string)'      

Ok, let’s go back and fix it:

using testing.classes.abstracts;
using testing.interfaces;
namespace testing.classes
{
    public class childClass: baseClass, interface1
    {
       public string givemeText(string text)
       {
           return text;
       }
    }
}


As you can see there is a difference and they are both useful. You would read the explanation saying that one is “Is A” situation and the other is a “Can-Do-This” “…

I guess that explanation sound kind of smart. Me, I’m more practical and I believe a better way to understand this is by answering the question: when to use one or the other? Stick around and I’ll try to answer that one.


Should we use them?

Yes, I believe we should use them. I always like to say: “It is a best practice”, even though sometimes I use that phrase to make things serious and scare people, in this case I’m not. Use them if:

1)      If is not a code that is for yourself only and is not a 1 or 2 month thing that you will put it away and will never use it again, then use abstract classes and interfaces if necessary to make your code easier to read.

2)      A project of Medium and over in size that other developers are involved and things like structure, organization, maintenance become important in the short – medium – long run then use them.

Important Note: you would never want to overdo something, “over-engineering”. Be careful with that. Everything in life should be in a balance. If you over engineer something then you are also making it hard to maintain, debug (during troubleshooting), and so on.

When:

when will you use them (abstract classes and/or interfaces)?

Use abstract classes for default functionalities, for classes that have things in common. That way if you need to update something that affects all your child classes then you just go to the abstract and change it there and BUM!, it goes to all of them.

If you try to do this with an interface that you might be broken your code and you will have to go to each class and make an update to get it working again.

Use interfaces… well I just gave you an example in the definition section. Basically you can apply multiple interfaces to the same class, which is a benefit. It provides structure and boundaries. Once you implement them then your class it is “force” to use the methods define in it, so it provides…I would say consistency.


References:

http://codeofdoom.com/wordpress/2009/02/12/learn-this-when-to-use-an-abstract-class-and-an-interface/

http://www.techrepublic.com/blog/programming-and-development/when-to-use-interfaces-instead-of-classes/2858

http://stackoverflow.com/questions/48605/why-do-most-system-architects-insist-on-first-coding-to-an-interface

http://stackoverflow.com/questions/56867/interface-vs-base-class

http://stackoverflow.com/questions/4790740/interface-abstract-class-coding-standard

http://msdn.microsoft.com/en-ca/library/k535acbf%28v=vs.71%29.aspx

If you are into PHP here are some good beginner examples for you:
http://php.net/manual/en/language.oop5.abstract.php

Trending posts

Democratizing AI

Democratizing AI is all about empowering others to use it, by making it available to them. Audiences, such as marketers in a company, will be able to access AI capabilities as part of their MarTech solutions, without the need of being technical. It could also be schools, where the younger generations are learning how to use it in responsible, secure, innovative, and creative ways. This is the year where companies, after discovery phases and teams experimenting, are looking to activate and take advantage of the AI advances. Generated with Microsoft Designer   And so, questions emerge, such as “What to democratize when leveraging AI?” There are common scenarios, as well as specific ones, that will depend on the company, and the industry they belong to. A common scenario, seen in many industries, when democratizing data is the data visualization and reporting . In digital marketing, as an example, data scientists and data analysts can automate reporting, making them available to the c...

Productivity framework for 2024

Recently I was at a Christmas party and I found myself giving advice to a friend on being more productive. I shared the approaches that I take which helped me become more productive at work and in my personal life. The conversation with my friend inspired me to share my approaches in this blog .  Photo by Moose Photos from Pexels   My productivity framework has five key pillars and to remember them I use the mnemonic, POFOR = P lan your tasks, O rganize yourself, F ocus on your tasks, O ptimize yourself with habits and R eflect to ensure you are being productive on the right tasks. Plan Planning is very crucial as it sets the tone for the rest of the pillars. I always found I was more productive when I planned my tasks compared to when I didn’t, and hence planning has become my rule of thumb. I recommend taking 30 minutes at the end of each day to plan your next day. This means prioritizing your tasks and blocking your calendar accordingly. By not doing so, you are at risk o...

SRE, DevOps and ITOps

 If you are wondering what the differences between the SRE and DevOps are, as well as how these roles work with ITOps within an organisation then you are not alone; and best of all you are on the right blog post. Often enough business units in a company get confused, assigning the ServiceNow or Jira tickets or any other ticketing system of your preference, to the wrong group, and even having the incorrect expectations when doing resourcing. Let us go through definitions, insights and scenarios that will help you understand the difference. DevOps software development operations - AI Generated When it comes to DevOps and SRE, then you might be wondering which practice came first. While SRE may have originated a bit earlier, internally at Google, DevOps came first publicly as a practice and started to be used by companies. A few years later was when Google decided to open SRE to the world after the publication of the "Site Reliability Engineering" book. Therefore, technically sp...

Effective framework to resolve conflict in the Workplace

 Conflicts are a part of our daily lives and are often unavoidable at work. Therefore, it's essential to have the tools to effectively manage conflicts and leverage them to our advantage - to spur new ideas, challenge and strengthen our beliefs, and evolve our perspectives when necessary. However, conflicts often trigger our fight-or-flight response and can cause chronic stress and mental fatigue and diminish our productivity. Having the right tools can help us face conflicts confidently.  AI Generated with Microsoft Copilot + Designer by Beolle   Recently, I took a course from Harvard ManageMentor® * to enhance my conflict resolution skills. I summarized the key takeaways from the course in the framework below to help you better prepare for resolving conflicts. The framework consists of six (6) parts Identify the type of conflict   Identify your own and your counterpart's conflict styles   Determine how you want to address the conflict   Prepare to resolve...

This blog uses cookies to improve your browsing experience. Simple analytics might be in place for pageviews purposes. They are harmless and never personally identify you.

Agreed