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

Small Language Models

 Open source models will continue to grow in popularity. Small Language Models (SLMs) are smaller, faster to train with less compute.  They can be used for tackling specific cases while being at a lower cost.  Photo by Tobias Bjørkli via Pexels  SLMs can be more efficient SLMs are faster in inference speed, and they also require less memory and storage.    SLMs and cost Small Language models can run on less powerful machines, making them more affordable. This could be ideal for experimentation, startups and/or small size companies. Here is a short list Tiny Llama. The 1.1B parameters AI Model, trained on 3T Tokens. Microsoft’s Phi-2. The 2.7B parameters, trained on 1.4T tokens. Gemini Nano.  The 6B parameters. Deepseek Coder

Key insights from "Atomic Habits" by James clear

I recently finished reading "Atomic Habits" by James Clear. The book was incredibly insightful. If you are looking to improve your habits, and achieve results while you are at it, then this book is for you. It may help you form new habits, and break bad one. Without further due, here are my top three takeaways. Photo by Nataliya Vaitkevich via Pexel, adapted by Beolle Takeaway 1:  The habit-forming loop: James outlines that the habit-forming loop consists of four stages Cue . The cue triggers the brain to expect a reward and is crucial for building automatic habits. It is typically associated with time, place, or feeling. For example, feeling bored could be a cue to the habit of using social media. Craving . This is the urge resulting from the cue. Using the above example, opening the social media app is the craving initiated by the cue of boredom. Response . An example of a response is the action of opening the social media app and using it. Reward . An example of reward i...

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