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.
- 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.
- 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.
- 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.
- 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.
- 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.
- Add a “Class Library” project and name it “SearchLibrary”.
- Add an interface “
ISearch
”. The naming convention for the interface is to prefix it with “I”.
- 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
- Add a class “
Search
”. This class implements the “ISearch
” interface.
- 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.
- Add a new console based project in the same solution.
- 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.
- Import the namespace “
SearchLibrary
”. This allows our console based application to have access to the ISearch
interface and Search
class.
- 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;
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.
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.
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
{
private const string strConection =
"Data Source=localhost;Initial Catalog=test;User Id=testUser;Password=welcome;";
#region IUserRepository Members
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());
}
}
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());
}
}
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; namespace Console_App
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("######## Consume DataLayer ##########");
IUserRepository userRep = new UserRepository();
userRep.AddNewUser("Bob", "Dylon");
userRep.DeleteUser(4);
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 :)
namespace DataLayerLINQToSQL
{
public class UserRepository: IUserRepository
{
public int GetTotalUsers()
{
}
public void AddNewUser(string username, string firstname)
{
}
public void DeleteUser(int userID)
{
}
}
}
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; namespace Console_App
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("######## Consume DataLayer ##########");
IUserRepository userRep = new AnotherUserRepository();
userRep.AddNewUser("Bob", "Dylon");
userRep.DeleteUser(4);
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 :)