.NET interview questions: - If we want to update interface with new methods, what is the best practice?
The biggest use of interface is to ensure that strict CONTRACT is followed between clients and components. So that when changes happen on the components clients do not have to change too much. In real world CONTRACTS between two parties do not change which implies that interfaces should also not change.
So if you want to add new methods or change methods in interfaces the best practice is to create new interfaces by inheriting. With this approach your older client who are using the interface stay happy and the new clients who want those new or changed methods get the benefits of the new functionality.
Let’s consider you have a simple interface called as “IView” which helps you to view data , below is the code for the same. Let’s consider that this interface is consumed by many clients.
Over a period of time some users demand “Edit” functionality as well but the rest of the users are happy with the ‘View” functionality and they do not want them to get affected by these changes. Now if you go and change this interface ( “IView”) a.k.a you will be disturbing everyone.
Figure: - update interface with new methods
So the best option would be to add a new interface i.e. “IEdit” which inherits from “IView”. So the “IEdit” will have the functionality for “Edit” as well as “View” because it’s also inheriting from “IView”. And the clients who are consuming “IView” do not need to update as “IView’ is not changed at all.
So putting this whole story in one single sentence for the interviewer.
See the following .NET interview questions video on Debug directive in C#: -