Interfaces are useful in order to add a level of abstraction early on in the design process. It will benefit the modularity of your code. If you have a big enough project (one that warrants using mocking) interfaces are useful, though for small projects this is most likely overkill. They can be used more than they need to be certainly, but if you take to heart the following guidelines you will know when to use inheritance and when to use an interface. Your code reusability and scalability will increase greatly when interfaces are used where appropriate!
The old explanation of when to inherit works nicely:
- Is a - inheritanceYour class is a subclass of a more generalized class, e.g.
HouseCat
inherits fromFeline
because a house cat "is a" feline. - Has a - member fieldA
LittleGirl
has a cat, so obviously she should not be a subclass toHouseCat
(she is not acat). It is best that she "has a"HouseCat
member field.class LittleGirl { int age; string name; HouseCat pet; }
- Performs - interfaceInterfaces should be used when a class or group of classes all have similar functionality, but when there is no obvious line of inheritance. Think of them as a certificate that says "this object performsthis functionality."For example, a
HouseCat
might inherit from Feline, but implement theICanHasCheeseburgers
(orICanHazChzbrgrsPlz
) interface. That way you have a BurgerJoint class with a methodpublic CheeseBurger Serve(ICanHasCheeseburgers patron)
and be able to pass eitherHumans
orHouseCats
to theServe
method in order to feed them aCheeseburger
.This is useful becauseHouseCat
does not inherit fromPerson
nor vice versa. However, they both perform acts involvingCheeseBurgers
No comments:
Post a Comment