Click here to Skip to main content
15,881,172 members
Articles / Programming Languages / C#

Using C# Interfaces to Make Applications Resilient to Changes

Rate me:
Please Sign up or sign in to vote.
4.74/5 (16 votes)
24 Feb 2011CPOL6 min read 87.8K   994   38   28
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:

C#
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:

C#
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:

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

C#
// 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.

C#
//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:

C#
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 :)

C#
//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...

C#
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 :)

License

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


Written By
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

 
QuestionWhy don't we use: Search mySearch Pin
kvuong826-Jun-13 6:13
kvuong826-Jun-13 6:13 
AnswerRe: Why don't we use: Search mySearch Pin
colinwiseman14-Aug-13 15:08
colinwiseman14-Aug-13 15:08 
Generalat last i found a real useful example of using interfaces Pin
tux@ddictor2-Apr-13 4:37
tux@ddictor2-Apr-13 4:37 
QuestionAny related stuff Pin
vuckovikmarko13-Feb-13 2:17
vuckovikmarko13-Feb-13 2:17 
GeneralI like this article Pin
Rocky Sharma4-Dec-12 11:27
Rocky Sharma4-Dec-12 11:27 
GeneralMy vote of 2 Pin
fera17-Oct-11 10:39
fera17-Oct-11 10:39 
GeneralRethrowing Exceptions Pin
Justin Helsley24-Feb-11 13:08
Justin Helsley24-Feb-11 13:08 
GeneralRe: Rethrowing Exceptions Pin
Vikram Lele24-Feb-11 18:36
Vikram Lele24-Feb-11 18:36 
GeneralRe: Rethrowing Exceptions Pin
milan24-Feb-11 21:20
milan24-Feb-11 21:20 
GeneralRe: Rethrowing Exceptions Pin
JV999924-Feb-11 23:03
professionalJV999924-Feb-11 23:03 
GeneralRe: Rethrowing Exceptions Pin
milan24-Feb-11 23:31
milan24-Feb-11 23:31 
GeneralMy vote of 5 Pin
Roger Wright22-Feb-11 12:05
professionalRoger Wright22-Feb-11 12:05 
GeneralRe: My vote of 5 Pin
milan23-Feb-11 7:41
milan23-Feb-11 7:41 
GeneralMy vote of 3 Pin
dan!sh 22-Feb-11 8:25
professional dan!sh 22-Feb-11 8:25 
Decent as a beginner's article. How about adding cases where one implements two interfaces with same method names? Or few combination of class inheritance and interface implementation.
GeneralRe: My vote of 3 Pin
milan23-Feb-11 0:56
milan23-Feb-11 0:56 
Question[My vote of 1] you marked this as Intermediate?? Pin
Seishin#22-Feb-11 0:27
Seishin#22-Feb-11 0:27 
AnswerRe: [My vote of 1] you marked this as Intermediate?? Pin
milan22-Feb-11 7:30
milan22-Feb-11 7:30 
GeneralRe: [My vote of 1] you marked this as Intermediate?? Pin
Henry Minute22-Feb-11 8:08
Henry Minute22-Feb-11 8:08 
GeneralRe: [My vote of 1] you marked this as Intermediate?? Pin
dan!sh 22-Feb-11 8:27
professional dan!sh 22-Feb-11 8:27 
GeneralRe: [My vote of 1] you marked this as Intermediate?? Pin
Yusuf22-Feb-11 8:35
Yusuf22-Feb-11 8:35 
AnswerRe: [My vote of 1] you marked this as Intermediate?? Pin
Grav-Vt28-Feb-11 11:44
Grav-Vt28-Feb-11 11:44 
GeneralRe: [My vote of 1] you marked this as Intermediate?? Pin
Seishin#28-Feb-11 21:48
Seishin#28-Feb-11 21:48 
GeneralRe: [My vote of 1] you marked this as Intermediate?? Pin
milan1-Mar-11 8:17
milan1-Mar-11 8:17 
GeneralRe: [My vote of 1] you marked this as Intermediate?? Pin
Seishin#1-Mar-11 22:48
Seishin#1-Mar-11 22:48 
GeneralRe: [My vote of 1] you marked this as Intermediate?? Pin
milan2-Mar-11 1:52
milan2-Mar-11 1:52 

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

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