Interfaces - The Concept

Posted by Ahmed Tarek Hasan on 9/14/2012 12:05:00 AM with 2 comments
What is the meaning of the word "interface" in English?
If you look up the word "interface" in the dictionary you will find that it can be defined in more than one way as follows:
  • A surface regarded as the common boundary of two bodies, spaces, or phases
  • The facts, problems, considerations, theories, practices, etc., shared by two or more disciplines, procedures, or fields of study: the interface between chemistry and physics
  • A common boundary or interconnection between systems, equipment, concepts, or human beings
  • Communication or interaction: Interface between the parent company and its subsidiaries has never been better
  • A thing or circumstance that enables separate and sometimes incompatible elements to coordinate effectively: The organization serves as an interface between the state government and the public

What is the meaning of "interface" in C#?
Sometimes when you are writing some code, you feel that you need to make your code somehow generic and independent on a single type of objects/classes because you believe that your logic can be applied on wide range of different classes and objects given that these objects share some common features. So, while you are writing your logic, you need to be confident that the class or object you are dealing with and that you don't know its type at the moment of writing your code will not cause any troubles or problems and will undergo the exact logic you want.

To understand what I really mean here, let's try to imagine the scenario below:
  • You want to write a math helper static class which provide some static methods to be used to carry out some mathematical operations
  • One of these operations is comparing two numerical values, if the first value is greater, return +ve int, if equal, return 0, else, return -ve int
  • So, you may write a method to compare two int numbers using the code (intNum1.CompareTo(intNum2))
  • And another method to compare two double numbers using the code (doubleNum1.CompareTo(doubleNum2))
  • And another one to compare two float numbers using the code (floatNum1.CompareTo(floatNum2))
  • And another one to compare two long numbers using the code (longNum1.CompareTo(longNum2))

This will work but this is somehow bad. You feel that this is not what you really needed and imagined when you were thinking of your class. You want to use this class and its helper methods regardless the type of the input because at last it just uses the same logic whatever the input type is given that it has a "CompareTo" member method. Not only the same logic, but also the same line of code except for the type of the numerical value.

Also, why do you need to write the same logic 4 times????? this is not logical and this redundancy in logic and code may cause you problems in the future especially if you decided to apply some changes to the logic.

So, when you analyze the problem, you will find that it would be so great if you are sure that the input type for your method has a member method called "CompareTo" which applies the same logic as it is expected. Then you can apply your logic without any problems and it would be enough to just write one method to apply the logic whatever the input type is.

So, in other words, you need a trustworthy contract between your method and the compiler. This contract will guarantee that the compiler will not by any mean let the user of your class call your one method passing an input type which doesn't have the member method "CompareTo" which applies the same required logic. This way you can apply your logic without any problems.

Also, this way you can make sure that any other class which follows this contract can be passed as an input to your method although you never knew about it before, but your logic can still apply on it.

This contract is the interface :)

So, in IT words, the interface is a contract which guarantees that every class implementing it has some specific member definitions. Note that i said definitions not implementations and that is because two classes can implement the same interface but have different implementations to those members guaranteed by their common interface.

So, if an interface includes into its definition a method with the header "void WriteToLogFile()", then for class A to implement this interface, it should have a member method with the header "public void WriteToLogFile()". Also, for class B to implement this interface, it should have a member method with the header "public void WriteToLogFile()". The implementation of this method in both class A and B may differ.


So, How can we use interfaces in the math helper class?
Without using interfaces, you would have written your method as follows

 public static int CompareValues(int num1, int num2)  
     {  
       return num1.CompareTo(num2);  
     }  
   
     public static int CompareValues(double num1, double num2)  
     {  
       return num1.CompareTo(num2);  
     }  
   
     public static int CompareValues(long num1, long num2)  
     {  
       return num1.CompareTo(num2);  
     }  
   
     public static int CompareValues(float num1, float num2)  
     {  
       return num1.CompareTo(num2);  
     }  

But, after using interfaces, the code will be

 public static int CompareValues(IComparable num1, IComparable num2)  
     {  
       return num1.CompareTo(num2);  
     }  

If you have a look on the "IComparable" interface, you will find its definition as follows:

 // Summary:  
   //   Defines a generalized type-specific comparison method that a value type or  
   //   class implements to order or sort its instances.  
   [ComVisible(true)]  
   public interface IComparable  
   {  
     // Summary:  
     //   Compares the current instance with another object of the same type and returns  
     //   an integer that indicates whether the current instance precedes, follows,  
     //   or occurs in the same position in the sort order as the other object.  
     //  
     // Parameters:  
     //  obj:  
     //   An object to compare with this instance.  
     //  
     // Returns:  
     //   A 32-bit signed integer that indicates the relative order of the objects  
     //   being compared. The return value has these meanings: Value Meaning Less than  
     //   zero This instance is less than obj. Zero This instance is equal to obj.  
     //   Greater than zero This instance is greater than obj.  
     //  
     // Exceptions:  
     //  System.ArgumentException:  
     //   obj is not the same type as this instance.  
     int CompareTo(object obj);  
   }  

This interface defines only a single method with the name "CompareTo", takes input parameter of type object and returns int.

You will find that all of the numerical types (int, double, float, long) implement this interface and that's what we depend on to apply our logic.


What types of members can an interface have?
An interface definition can have:
  1. Method definitions
  2. Property definitions
  3. Event definitions
  4. Indexer definitions
All members of the interface definition should be public. Due to this restriction, it is not allowed to write any access modifiers (public, private, protected, internal, ....) inside an interface definition even if it is public.


So, when do i need to use interfaces?
Interfaces is a concept which can be applied in so many cases and if you know about design patterns you will really embrace the power of interfaces. But, to simplify the whole concept in just few words, interfaces is about "Abstraction rather than Implementation".

This means that, when you design some logic, try to come out with the most abstract meaning and logic of your logic. If you found that your logic could be applied on a group of classes/objects given that they have certain common features or behavior, then you should think of interfaces. But, don't confuse these common features with implementation, they may have different implementation of these common features and you still can apply your logic.

Also, you can write your own interfaces to be used through your system classes/objects to form some kind of contracts to control the way your system classes/objects communicate in a loosely coupled manner. Why?????? because you prefer abstraction to implementation :)


Update:
The new post One Of The Methodologies To Write Clean, Maintainable & Extensible Software is now available including a practical example on how to make use of interfaces.


Anything else?
Yes, there is another concept in C# similar to interfaces called "Abstract Classes" but with some differences.


So, what about "Abstract Classes"?
You will find that always whenever interfaces are mentioned abstract classes are mentioned too with some comparisons between both. But, i didn't do so cause i wanted to address the main concept first which is mainly the same. Once you understand the main concept behind interfaces, it will be so easy to understand abstract classes.


So, now what?
Now, i really encourage you to search and read more about interfaces (and abstract classes) and its applications in design patterns. Then, you will really understand how you can enhance your design and coding skills in a great way using interfaces (and abstract classes).


Finally, i hope this helped you to understand the main concept behind interfaces and its important role in "Abstraction rather than Implementation" concept.

Good Luck :)


Categories: , ,