Hi all, I got a basic doubt when to use interfaces or do we really want to use it. I will give a small example to expalin my doubt.
I have a Interface ISample which contains 2 methods A and B. I write a class ClsSample to implement this Interface. In that class I have to give implementaion to methods A and B.
so I will use this Interface by saying ISample isample = new ClsSample(); isample.A(); isample.B();
Instead I can very well directly call the ClsSample class ClsSample csample = new ClsSample(); isample.A(); isample.B();
So if I have defined this A and B method directly in the ClsSample class I don't need a Interface at all here. So I am really confused when I should use a Interface
Can anyone please tell me a thumb rule when to use a Interface.
Think of a manual car (stick shift if you are American). You know how to change gear up or down. You can do this whether you drive a Honda or a Ford. This is because the interface for a gear is well defined and understood. This is despite the fact that Honda and Ford make their gear boxes (transmissions) very differently.
In an OO world you might have a Transmission interface with FordTrasmission and HondaTransmission implementations. The point being the driver just uses the interface and it works whatever car they are in.
When you use interfaces for the type of your variables and arguments you avoid being locked into any one implementation. For example, if you write a method:
you can only call this method with a linked list. Then one day you have an ArrayList and you'd really like to call doSomething(). You have to make a new LinkedList before you can call it. But if you wrote:
then you can call doSomething with any implementation of List. Now the code is much more useful and less likely to have to change because you'd like to use another list. That's the value of "abstraction" and interfaces. Neat, huh?
Use an interface always. Or, use an interface when you are using an interface e.g. calling upon the contract of an API. There are lots of "yeah buts", but they are all contrived (at least that I have seen). This means that *all* methods (regardless of access scope) should be specified on an interface. This leads to the profound assertion that private methods violate encapsulation (prefer a private interface).
The two most prolific abominations that I observe are: 1) do not use an interface when the client/provider relationship is self-referential e.g. in a private context or "when nobody but me will use this contract". It is amusing to observe the consequences of engaging in this practice. Often it is attributed elsewhere by the sufferer making it more amusing (or frustrating if you lack patience). 2) A bunch of gumph related to Test Driven Development (TDD) - I won't begin explaining how messed up all that is.
Ernest Friedman-Hill
,
author and iconoclast
staff