Click here to Skip to main content
Click here to Skip to main content

Using C# Interfaces to Make Applications Resilient to Changes

, 24 Feb 2011
Rate this:
Please Sign up or sign in to vote.
Taking advantage of Interfaces to make applications resilient to changes.

Introduction

There is a plethora of books and articles on this topic mostly on object oriented programming topics. This article is my understanding of it and just wanting to share a lovely principle and utilizing it to create a future proof system that can adapt to changes. We will be looking at how we can take advantage of interface based programming by writing a simple application in C#. The idea can be easily transferred to write data-driven applications emerging from various data stores – database, files, Web Services, etc.

Why is it important?

The benefits of using interface based programming, as I can think of while writing this small piece of article, are outlined below. Please note that there might be many others.

  1. Enables to write loosely coupled systems. With the help of interfaces, if required in future, we can simply change the implementation thus making it easy for our application to adapt to changes.
  2. Developers’ roles are segregated. Developers writing interface based components don’t have to worry about how it’s being implemented. They only need to know how to invoke functionalities available within it. UI developers can start working on the UI without a concrete implementation of the interface. At the same time, component developers can concentrate in implementing the agreed interface definition.  This enables parallel development as one does not have to depend on another’s work during the development process.
  3. As long as the interface definitions are not changed, adding new features or re-implementing existing features for various reasons like changes in business rules will not break the existing system, rather makes it rich and efficient over a period of time.
  4. Generates maintainable and clean source code – UI related code is separated from other parts of the system like data access layer and business/domain related layer.
  5. Unit testing that every developer should embrace can be utilised. It can be performed independent of the UI or any other layer consuming functionalities of the interface based classes.

What is an interface?

Before going forward, let me make myself clear that when I use the word interface, it is not the end-user interface that has visual components, rather it is a bridge that developers use underneath their heap of classes to interact with other classes. Defining an interface allows a component of the system to communicate with another without knowing how it has been implemented. A good analogy would be a computer hardware repairer who does not have to know how a circuit board is designed in the hard disk or the mother board as long as he knows that if he replaced it by a new one with the correct specification, it would work perfectly. The same principal can be applied in software engineering. You write your own world changing algorithms and expose it to other developers via an interface to integrate into their different user interfaces. It can be an ASP.NET application or a Windows based form or even a mobile device based application. It opens a whole new world to components based programming. Like our hardware repairer, we can have software components designed and implemented.  These components can be the building blocks of our new enterprise applications.

How is this done in C#?

A. Defining the interface

Fire up your Visual Studio.

  1. Add a “Class Library” project and name it “SearchLibrary”.
  2. Add an interface “ISearch”. The naming convention for the interface is to prefix it with “I”.
  3. Define a method within the interface called “GetSearchResult” with a string parameter, and a return type of List<string>.

Your interface definition should look like:

namespace SearchLibrary
{
    interface ISearch
    {
        List<string> GetSearchResult(string searchPhrase);
    }
}

Now as long as both the UI developer and the component developer agrees to this interface definition, they can start working in parallel. One concentrates on the implementation and the other starts to work on the end user interface.

B. Implementing the interface

  1. Add a class “Search”. This class implements the “ISearch” interface.
  2. It is a must to implement method(s) defined within the interface. In our case, we need to implement the GetSearchResult(..) method.  Look carefully in the class declaration to see how it is done - class_ name : interface_name.

The “Search” class should look like:

namespace SearchLibrary
{
    public class Search:ISearch
    {
        public List<string> GetSearchResult(string searchPhrase)
        {
            searchPhrase = searchPhrase.ToUpper();
    
            List<string> sports = new List<string> { "Football", 
              "Volleyball", "Basketball", "Badminton", "Baseball", 
              "Swimming", "Rugby", "American Football", "Hockey", "Cricket" };

                List<string> results = new List<string>();
                results = (from sport in sports
                        where sport.StartsWith(searchPhrase)
                        select sport).ToList();

                return results;
            }
        }
    }

The component developer starts implementing the interface. Although over a period the implementation might change for a particular method definition, it will not break the existing system as long as the earlier definition has not changed. Adding a new method/function definition will not break the system, rather makes it rich!

C. Console based application

To make the example straightforward, I will depend on a console based application as the end user interface. It can be replaced with a web based or window based form fairly easily.

  1. Add a new console based project in the same solution.
  2. Add references to your “SearchLibrary” project if both the projects are within the same solution. If they are not, then reference “SearchLibrary.dll” located in the bin folder.
  3. Import the namespace “SearchLibrary”. This allows our console based application to have access to the ISearch interface and Search class.
  4. Now the tricky bit is we declare a variable “mySearch” of type “ISearch” and assign the instance of the “Search” class. The idea being we communicate via the interface.

Your console application should like:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SearchLibrary; //Forget not to import this namespace

namespace ConsoleSearchApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("#### Interface based Programming example");

            ISearch mySearch = new Search();
            List<string> results = mySearch.GetSearchResult("F");
            Console.WriteLine("Search results: ");
            foreach (string result in results)
            {
                Console.WriteLine(result);
            }
            Console.ReadLine();
        }
    }
}

As mentioned in the introduction, the sample principle can be used to write a data access layer. I will leave the implementation to the readers who, I sure, know how to access a database in .NET using ADO.NET and LINQ to SQL. Therefore, allow me only to define the interface and the skeleton structure of the implementing class.

Let’s say we are working with a user related SQL table to perform the usual actions. We can define the user related methods within the interface IUserRepository.  The SQL scripts to create a table and insert dummy records and Stored Procedures are supplied along with the running source code.

// IUserRepository.cs

namespace DataLayer
{
    public interface IUserRepository
    {
        int GetTotalUsers();
        void AddNewUser(string fName, string lName);
        void DeleteUser(int userID);
    }
}

ADO.NET implementation

The first implementation is purely based on ADO.NET programming against SQL Server. For better performance and easier to read/maintain code, Stored Procedures are used even though they are not doing anything magical apart from normal insert/delete operations in this example, but in real-life applications, there will be a necessity to join multiple tables to get a result back to the user interface. Following such a pattern helps immensely in writing clean, easy to maintain, and high performance data-driven applications.

//UserRepository.cs implementation using ADO.NET
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace DataLayer
{
    public class UserRepository: IUserRepository
    {
        //Change connection string as per your sql server
        //Store it in App.Config 
        private const string strConection = 
          "Data Source=localhost;Initial Catalog=test;User Id=testUser;Password=welcome;";
        #region IUserRepository Members
        /// <summary>
        /// Returns Total Number of Users using Stored Procedure "SampleDb_TotalUsers"
        /// </summary>
        /// <returns>int</returns>
        public int GetTotalUsers()
        {
            try
            {
                int totalUsers = -1;
                SqlConnection myCon = new SqlConnection(strConection);
                myCon.Open();
                SqlCommand com = new SqlCommand();
                com.Connection = myCon;
                com.CommandType = CommandType.StoredProcedure;
                com.CommandText = "SampleDb_TotalUsers";
                SqlParameter paramOut = new SqlParameter("@TotalUsers", DbType.Int32);
                paramOut.Direction = ParameterDirection.Output;
                com.Parameters.Add(paramOut);
                com.ExecuteNonQuery();
                if (com.Parameters["@TotalUsers"] != null)
                {
                    totalUsers = Convert.ToInt32(com.Parameters["@TotalUsers"].Value);
                }
                myCon.Close();
                return totalUsers;
            }
            catch (SqlException sExp)
            {
                throw new Exception(sExp.ToString());
            }
            catch (Exception exp)
            {
                throw new Exception(exp.ToString());
            }
        }
        /// <summary>
        /// Inserts new user 
        /// </summary>
        /// <param name="fName">string</param>
        /// <param name="lName">string</param>
        public void AddNewUser(string fName, string lName)
        {
            try
            {
                SqlConnection myCon = new SqlConnection(strConection);
                myCon.Open();
                SqlCommand com = new SqlCommand();
                com.Connection = myCon;
                com.CommandType = CommandType.StoredProcedure;
                com.CommandText = "SampleDb_AddUser";

                SqlParameter paramFirstName = 
                  new SqlParameter("@FirstName", SqlDbType.NVarChar, 50);
                paramFirstName.Value = fName;
                paramFirstName.Direction = ParameterDirection.Input;
                com.Parameters.Add(paramFirstName);

                SqlParameter paramLastName = 
                  new SqlParameter("@LastName", SqlDbType.NVarChar, 50);
                paramLastName.Value = lName;
                paramLastName.Direction = ParameterDirection.Input;
                com.Parameters.Add(paramLastName);

                com.ExecuteNonQuery();
                myCon.Close();
            }
            catch (SqlException sExp)
            {
                throw new Exception(sExp.ToString());
            }
            catch (Exception exp)
            {
                throw new Exception(exp.ToString());
            }
        }
        /// <summary>
        /// Deletes user based on ID
        /// </summary>
        /// <param name="userID"></param>
        public  void DeleteUser(int userID)
        {
            try
            {
                SqlConnection myCon = new SqlConnection(strConection);
                myCon.Open();
                SqlCommand com = new SqlCommand();
                com.Connection = myCon;
                com.CommandType = CommandType.StoredProcedure;
                com.CommandText = "SampleDb_DeleteUser";

                SqlParameter paramUserID = 
                  new SqlParameter("@UserID", SqlDbType.Int,32);
                paramUserID.Value = userID;
                paramUserID.Direction = ParameterDirection.Input;
                com.Parameters.Add(paramUserID);

                com.ExecuteNonQuery();
                myCon.Close();
            }
            catch (SqlException sExp)
            {
                throw new Exception(sExp.ToString());
            }
            catch (Exception exp)
            {
                throw new Exception(exp.ToString());
            }
        }
        #endregion
    }
}

Our simple console application makes use of the above data access repository as follows. Please remember to add a reference to the above class library project before importing the right namespace. The console application code should look like below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DataLayer; //Our data Access Namespace
namespace Console_App
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("######## Consume DataLayer ##########");
                //Add New User
                IUserRepository userRep = new UserRepository();
                userRep.AddNewUser("Bob", "Dylon");
                //Delete User
                userRep.DeleteUser(4);
                //Total Users in the table 
                int totalUsers = userRep.GetTotalUsers();
                Console.WriteLine("Total Number of Users:" + totalUsers);
                Console.ReadLine();
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp.Message);
                Console.ReadLine();
            }
        }
    }
}

LINQ to SQL implementation

Later in the future, there might be a need to re-implement the same system using an ORM technology like LINQ to SQL. As we have developed our application based on “interface” definitions, we can simply plug-in a new implementation without affecting the presentation or the UI layer. All we need is to implement the IUserRepository interface using LINQ to SQL and instantiate the right class object in the UI layer.

Assume we managed to do so in the AnotherUserRepository class. It might look as follows. I will leave the real implementation job to you Smile | :)

//AnotherUserRepository.cs implementation using LINQ TO SQL
namespace DataLayerLINQToSQL
{
    public class UserRepository: IUserRepository
    {
        public int GetTotalUsers()
        {
            //LINQ TO SQL
        }
        public void AddNewUser(string username, string firstname)
        {
            //LINQ TO SQL
        }
        public void DeleteUser(int userID)
        {
            //LINQ TO SQL
        }
    }
}

The UI layer (the above console based application) code just needs to import the right namespace and instantiate the right class.

Here is the code snippet...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DataLayerLINQToSQL; //Our new data Access layer namespace
namespace Console_App
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("######## Consume DataLayer ##########");
                //Add New User
                IUserRepository userRep = new AnotherUserRepository();
                userRep.AddNewUser("Bob", "Dylon");
                //Delete User
                userRep.DeleteUser(4);
                //Total Users in the table 
                int totalUsers = userRep.GetTotalUsers();
                Console.WriteLine("Total Number of Users:" + totalUsers);
                Console.ReadLine();
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp.Message);
                Console.ReadLine();
            }
        }
    }
}

The idea of moving data access related code into repository classes is called the “Repository Pattern” which forms a very important concept in the Model-View-Controller architecture.

Conclusion

I hope we are convinced of one very simple principle – with the use of interface definitions, it is possible to write loosely coupled applications that can adapt to changes.

Enjoy programming Smile | :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

milan
Software Developer
United Kingdom United Kingdom
Milan has been developing commercial applications over a decade primarily on Windows platform. When not programming, he loves to test his physical endurance - running far away to unreachable distance or hiking up in the mountains to play with Yaks and wanting to teach 'Yeti' programming!

Comments and Discussions

 
GeneralRethrowing Exceptions PinmemberMW_Justin24-Feb-11 13:08 
GeneralRe: Rethrowing Exceptions PinmemberVikram Lele24-Feb-11 18:36 
GeneralRe: Rethrowing Exceptions Pinmembermilan24-Feb-11 21:20 
GeneralRe: Rethrowing Exceptions PinmemberJV999924-Feb-11 23:03 
GeneralRe: Rethrowing Exceptions Pinmembermilan24-Feb-11 23:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140721.1 | Last Updated 24 Feb 2011
Article Copyright 2011 by milan
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid