Code design:Simple use of interfaces

by sunil ravulapalli /6. July 2010 20:00 /software-design /Comments (0)

In short, the answer is 'flexibility'. I am not going to go into any complex detailed examples in this post. This post will just set up a base for future posts on interfaces. Lets begin with 2 classes as show below.

public class EmployeeRepository
{
  public DataSet GetAll()
  {
     string connectionString = "*********"
     DataSet employee = new DataSet();   
     using (SqlConnection connection = new SqlConnection(connectionString))
     {
        string queryString = "SELECT EmpId, EmpName FROM Employee";
        SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);

        adapter.Fill(employee, "Employees");
        return employee;
     }
  }
}

public class CustomersRepository
{
  public DataSet GetAll()
  {
     string connectionString = "*********"
     DataSet customers = new DataSet();
     using (SqlConnection connection = new SqlConnection(connectionString))
     {
        string queryString = "SELECT CustomerId, CustomerName, FROM Customer";
        SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);

        adapter.Fill(customers, "Customers");
        return customers;
     }
  }
}

Normally, we would use these classes like this:

EmployeeRepository employeerepository = new EmployeeRepository();
DataSet dataset = repository.GetAll();

and

CustomerRepository customerrepository = new CustomerRepository();
DataSet dataset = repository.GetAll();

Now, lets redesign our classes using interfaces?How do we do that? Notice, that both our classes have the same method called "GetAll()" with the "same return type". With that observation lets make an interface. It looks like this

public interface IRepository
{
    DataSet GetAll();
}

Now, our classes can be made to look like this:

public class EmployeeRepository : IRepository
{
   public DataSet GetAll()
   {
      //Same as before
   }
}
public class CustomersRepository : IRepository
{
   public DataSet GetAll()
   {
     //Same as before
   }
}

Great, we are now using interfaces! But wait, what good is it? It just added more code to my program! The real good will come in how we can instantiate our classes and then call our methods. Look at the following implementaion code:

IRepository repository = new EmployeeRepository();
DataSet dataset = repository.GetAll();

and

IRepository repository = new CustomerRepository();
DataSet dataset = repository.GetAll();

Notice, that we are now using IRepository for both implementations rather EmployeeRepository and CustomerRepository to call our "GetAll()" method i.e. we are now using a common interface rather than a concrete class. Although this may not be a "blow your mind" example of interface usage, it definitely forms basis for understanding things such as "Dependency Injection(DI)" etc. which will "blow your mind"!.

blog comments powered by Disqus