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

AGILE For DIGITAL AGENCIES

Introduction Some Digital agencies have a project process where waterfalls still plays a big part of it, and as far as I can tell, the tech team is usually the one suffering as they are at the last part of the chain left with limited budget and time for execution. I do believe that adopting an Agile approach could make a Digital Agency better and faster. In this article I’m presenting you just another point of view of why it make sense looking at Agile Methodology.  Why Agile for a Digital Agency? The Agile movement started in the software development industry, but it has being proven to be useful in others as well. It becomes handy for the type of business that has changing priorities, changing requirements and flexible deliverables. In the Digital Agency of today you need a different mindset. Creative will always play a huge role (“the bread and butter”). But the “big guys” need to understand that without technology there is no Digital Agency. Technical resources are

AI with great power comes responsibility

Generative AI continues to be front and centre of all topics. Companies continue to make an effort for making sense of the technology, investing in their teams, as well as vendors/providers in order to “crack” those use cases that will give them the advantage in this competitive market, and while we are still in this phase of the “AI revolution” where things are still getting sorted.   Photo by Google DeepMind on Unsplash I bet that Uncle Ben’s advise could go beyond Peter Parker, as many of us can make use of that wisdom due to the many things that are currently happening. AI would not be the exception when using this iconic phrase from one of the best comics out there. Uncle Ben and Peter Parker - Spiderman A short list of products out there in the space of generated AI: Text to image Dall.E-2 Fotor Midjourney NightCafe Adobe Firefly

Designing Habit Forming Mobile Application

Mobile Applications have become an integral part of our daily lives - we use mobile apps as alarm clocks to wake us up in the morning, to create to do lists when we start our day, to communicate with our colleagues at work via apps like Skype. We even check reviews of restaurants to visit on apps like Yelp and we seek entertainment on apps like Netflix and spotify. So what drives us to use these apps so seamlessly in our daily lives? Why we prefer some apps over others? Is there a science behind designing successful mobile apps like Facebook?  Photo by Peter C from Pexels A study in US revealed that a user between the age of 18 and 44 visits the Facebook app on average 14 times a day [1]. This shows that using the Facebook app is a daily routine for many of its users. This makes Facebook a great example of a habit forming mobile app which is designed with human psychology in mind that encourages habit forming behavior in its users .   I recently attended a seminar on the de

Research around JIRA vs TFS

By: Carlos G.    An opportunity came from a colleague to discuss the case of company “X” for improving the ALM by introducing tools to this company. The challenge was to decide between Microsoft and Attlasian . He came to me because I’m a Microsoft kind of guy and he wanted the opinion from my perspective, not as a consultant, but as a friend of what he was trying to accomplish. He said that even though I was inclined to a technology I was able to explore other things and be “fair”. I agreed to be a part of his research because of 3 things: because of my curiosity I'm always willing to learn new techy stuff. Sometimes is good to be the dumbest one of the group. You learn so much! This was a story that I could blog about. (Of course no names are used in this post). My first impression was thinking “cool”; let’s compare Visual Studio TFS vs JIRA. Immediately I got a comment back with: “ Sure but JIRA by itself is more like an issue tracker in simple terms ”. That sa

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