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

CRM - Overview Diagram

CRM is an interesting topic. I had the opportunity to work for a company where I participated in a project for the integration of: Microsoft Dynamics GP Microsoft Dynamics CRM Sharepoint (for the intranet)     I’ve also worked in the Digital Agency industry, involved in Web App solutions, where CRM strategies play an important role. For a client (Eg: An online company in retail selling shoes) would be beneficial to find a Shop (Digital Agency) that understands CRM from the strategic point of view and also offers services using software tools that facilitate the finding of insights, track consumer behaviors and helps to provide a personalize experience to the consumer; bringing value to the business. There are CRM solution providers out there that a Shop can partner with. To name a couple: Salesforce SDL There could also be a case where a Shop can create their own custom solution that could have as their center piece a BI system, created as a produc

Gaming trends: What to expect

Gaming continues with an accelerated evolution and significant business growth. The incredible virtual worlds are receiving thousands of real-time players, becoming another avenue for networking, as well as entertainment. This is just impossible to ignore. The gaming industry is one of the most dynamic and innovative sectors, constantly evolving and adapting to new technologies, consumer preferences, and market opportunities. Photo by Mikhail Nilov via Pexels   Newzoo forecast the game market will grow to $217.9 billion in 2023. Newzoo 2020 Global Game Market Cloud and gaming There was a time, not too long ago, when you would buy your games and play them by inserting them into your console or computer. As more gamers demand access to high-quality games on any device, anywhere, anytime, cloud gaming will become a mainstream option for delivering games over the internet. Games are now becoming available via subscription model. An example of this is the Microsoft Xbox game pass and Xbox L

Analytics and Attribution models

The customer journey is packed with multiple touchpoints, making it challenging to determine which of these “moments” (actions taken by the user) have played the most significant role in the conversion of the customer.  Photo by Mikael Blomkvist from Pexels Model attribution provides insights into how users interacts with your web and mobile apps. The decision-makers leverage the insights to understand what marketing efforts are driving “value”, allowing them to focus on the channels that provide the best Return on Investment (ROI).  There are several attribution models that can be used to assign credit. We will go through some of those in this article. Customer Journey - Beolle.com First touch attribution It is an awareness focus, being an introduction to the brand. This model gives the conversion credit to the first point of contact (i.e. a video or a social link).  Last touch attribution It is a model that gives the conversion credit entirely to the final touchpoint from which a lea

Your platform as a positive force in the world

If you are managing a platform, even if it is small, then you are leveraging one of the elements and popular channels used to build digital communities. These platforms, and channels, can come in the shape of websites, blogs, mobile apps, podcasts, vlogs, social media, or a combination of the ones mentioned. Photo by Tatiana Syrikova from Pexels   There are many reasons for building a community, such as sharing knowledge, promoting businesses, branding, the need for engaging with others, etc. However as Spiderman’s Uncle Ben said: “With great power comes great responsibility.” If you like to build better communities with more collaboration and less silos then how would you do it? How can communities come together to drive a “ positive force ”? The current world is mired in conflicts. How long are we willing to go on in such disarray? All the continents are in some kind of “a demonstration of partisanship, intolerance and selfishness”. There are nations in the Americas, Africa, Middl

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