In this section, we will delve further with Interfaces and see Why Interfaces are important for any Scalable, Extend-able and Testable. And, one of the key reasons which I believe basically for using Interfaces is to keep the code future proof and Maintainable. Now, let us consider a below case. Here, I have plain simple class with few properties in it. Now, this will serve as model for me populating the values.
In order to populate the same I am just using one repository as shown below.
Now, currently, above method is retuning all movies. Here, I am using Array as collection. Now, Let us look at the main program.
Here, it is printing same values one using simple Array and the other one using IEnumerable. In both the cases, it is working fine as IEnumerable is basically implemented by almost all the collections.
Now, let us consider for some reason developer wants to change the way it is returning data. Then, would like to use more feature rich collections like List.
At this instant, when I build the solution, then it will fail. It will print following message.
Basically, it’s saying that you cannot convert List to Arrays. Now, in order to fix the same, either we need to cast the same or we can just change the variable from Array to List as shown below.
With the above change in place, it will work fine, it will again produce the same result.
But, the conclusion is we didn’t have to change our Interface code because both Array and List implements IEnumerable. Therefore, whenever we are coding on the abstraction, we don’t care about the specific class coming back, only thing which we care about is the class which fulfills the contract. I hope you would have liked today’s discussion on Interfaces. In coming section, we delve further inside Interfaces. Thanks for Joining Me.
Download Code:- https://github.com/rahulsahay19/Extending-Interfaces
1,863 total views, 2 views today