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...

SLA-SLO-SLI and DevOps metrics

Companies are in need of the metrics that will allow them to stay in business by making sure they meet the expectations of their customers. The name of the game is higher customer satisfaction by winning their trust and loyalty. To do so, you want to provide good products and services. Therefore you need to find ways to monitor performance, drive continuous improvements and deliver the quality expected by the consumer in this highly competitive market. Photos from AlphaTradeZone via Pexel and Spacejoy via Unsplash SLAs, SLOs and SLIs are a good way to achieve the above. They allow clients and vendors to be on the same page when it comes to expected system performance. If we go one level deeper, vendors/providers work on NFRs (Non-Functional Requirements) when working on their solutions. NFRs define the quality attributes of a system. I bring them up because the relationship between them and the SLAs is that they provide, in a way, foundational aspects for the SLA-SLO-SL...

Take a break on zero emission day 2024

 Do you know how much you contribute to the daily emissions in your city? How much does the city you live in contribute within your country? How much does your country contribute to the emissions on our planet? Do you know its impact? Do you know why we have a zero emission day? Photo by Pixabay via Pexels Let us start by getting our acronyms right, shall we? You may have heard the term GHG emissions, wondering what that means. GHG stands for Green House Gas. These gases are part of the cause of the rising temperature on Earth. What is interesting about them  is that they absorb infrared radiation resulting in the greenhouse effect. Within the greenhouse gases you find carbon dioxide, methane, nitrous oxide, ozone, water vapour. The vast majority of carbon dioxide emissions by humans come from the burning of fossil fuels. Key sectors to consider for GHG Fuel Exploitation Power Industry Transport Waste Agriculture Buildings Industry combustion and processes Top GHG emissions...

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