Proper user of Interfaces in C#
We as software developers must always ...always remember to program to Interfaces NOT to Implementations. I'll tell you why. Everybody who's doing developing should know about software changes. We have to spent time on enhancements rather than the initial implementation. So what we require is a good design. IT IS A MUST, believe me. I had plenty of nightmares programming to bad designs. Check out the below UML design.
What we’re trying to do is to write our database method to the interface. Not to the concrete class.
Here is the complete code.
//interface to the DataHelper
public interface IDataHelper
{
void Connect();
void Execute();
}
//SqlDataHelper - using SQL database
public class SqlHelper :IDataHelper
{
public void Connect()
{
//SqlDataHelper Implementation
Console.WriteLine("Connectiing sql..");
}
public void Execute()
{
//SqlDataHelper Implementation
Console.WriteLine("executing Sql..");
}}
//OracleHelper - using Oracle database
public class OracleHelper : IDataHelper
{
public void Connect()
{
//SqlDataHelper Implementation
Console.WriteLine("Connectiing oracle..");
}
public void Execute()
{
//SqlDataHelper Implementation
Console.WriteLine("executing oracle..");
}}
public class UserDataBase
{
public UserDataBase()
{}
//method implementing to the IDataHelper interface
public static void CheckDB(IDataHelper help)
{
help.Connect();
help.Execute();
}
public static void Main(string[] args)
{
//Use 1
//Oracle as the Database
OracleHelper oraleHelper = new OracleHelper();
CheckDB(oraleHelper);
//Use 2
//Sql as the Database
SqlHelper sqlHelper = new SqlHelper();
CheckDB(sqlHelper);
}}
Later if you want to use MySql as the database simply write a class MySqlHelper & inherit from the IDataHelper class. You don’t have to change anything in the CheckDb() method. Its that simple. So try to program to interfaces whenever possible. Happy coding dudes..