Sorry to ask sich a generic question, but I’ve been studying these and, outside of say the head programming conveying what member MUST be in a class, I just don’t see any benefits.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There are two (basic) parts to object oriented programming that give newcomers trouble; the first is
inheritanceand the second iscomposition. These are the toughest to ‘get’; and once you understand those everything else is just that much easier.What you’re referring to is
composition– e.g., what does a class do? If you go the inheritance route, it derives from an abstract class (sayDogIS AAnimal) . If you use composition, then you are instituting a contract (A Car HAS A Driver/Loan/Insurance). Anyone that implements your interface must implement the methods of that interface.This allows for loose coupling; and doesn’t tie you down into the inheritance model where it doesn’t fit.
Where inheritance fits, use it; but if the relationship between two classes is contractual in nature, or
HAS-Avs.IS-A, then use an interface to model that part.Why Use Interfaces?
For a practical example, let’s jump into a business application. If you have a repository; you’ll want to make the layer above your repository those of interfaces. That way if you have to change anything in the way the respository works, you won’t affect anything since they all obey the same contracts.
Here’s our repository:
Now, I can implement that Repository in a class:
This separates the Interface from what is calling it. I could change this Class from Linq-To-SQL to inline SQL or Stored procedures, and as long as I implemented the
IUserRepositoryinterface, no one would be the wiser; and best of all, there are no classes that derive from my class that could potentially be pissed about my change.Inheritance and Composition: Best Friends
Inheritance and Composition are meant to tackle different problems. Use each where it fits, and there are entire subsets of problems where you use both.