How to Maximize Code Reuse in this Interface vs Inheritance C# Example - c#

Inspired by a great video on the topic "Favor object composition over inheritance" which used JavaScript examples; I wanted to try it out in C# to test my understanding of the concept, but it didn't go as well as I'd hoped.
/// PREMISE
// Animal base class, Animal can eat
public class Animal
{
public void Eat() { }
}
// Dog inherits from Animal and can eat and bark
public class Dog : Animal
{
public void Bark() { Console.WriteLine("Bark"); }
}
// Cat inherits from Animal and can eat and meow
public class Cat : Animal
{
public void Meow() { Console.WriteLine("Meow"); }
}
// Robot base class, Robot can drive
public class Robot
{
public void Drive() { }
}
The problem is that I want to add RobotDog class that can Bark and Drive, but not eat.
First solution was to create RobotDog as subclass of Robot,
public class RobotDog : Robot
{
public void Bark() { Console.WriteLine("Bark"); }
}
but to give it a Bark function we had to copy and paste the Dog's Bark function so now we have duplicate code.
The second solution was to create a common super class with a Bark method that then both the Animal and Robot classes inherited from
public class WorldObject
{
public void Bark() { Console.WriteLine("Bark"); }
}
public class Animal : WorldObject { ... }
public class Robot : WorldObject { ... }
But now EVERY animal and EVERY robot will have a Bark method, which most of them don't need. Continuing with this pattern, the sub-classes will be laden with methods they don't need.
The third solution was to create an IBarkable interface for classes that can Bark
public interface IBarkable
{
void Bark();
}
And implement it in the Dog and RobotDog classes
public class Dog : Animal, IBarkable
{
public void IBarkable.Bark() { Console.WriteLine("Bark"); }
}
public class RobotDog : Robot, IBarkable
{
public void IBarkable.Bark() { Console.WriteLine("Bark"); }
}
But once again we have duplicate code!
The fourth method was to once again use the IBarkable interface, but create a Bark helper class that then each of the Dog and RobotDog interface implementations call into.
This feels like the best method (and what the video seems to recommend), but I could also see a problem from the project getting cluttered with helpers.
A fifth suggested (hacky?) solution was to hang an extension method off an empty IBarkable interface, so that if you implement IBarkable, then you can Bark
public interface IBarker { }
public static class ExtensionMethods
{
public static void Bark(this IBarker barker) {
Console.WriteLine("Woof!");
}
}
A lot of similar answered questions on this site, as well as articles I've read, seem to recommend using abstract classes, however, wouldn't that have the same issues as solution 2?
What is the best object-oriented way to add the RobotDog class to this example?

At first if you want to follow "Composition over Inheritance" then more than half of your solutions don't fit because you still use inheritance in those.
Actually implementing it with "Composition over Inheritance" there exists multiple different ways, probably each one with there own advantage and disadvantage. At first one way that is possible but not in C# currently. At least not with some Extension that rewrites IL code. One idea is typically to use mixins. So you have interfaces and a Mixin class. A Mixin basically contains just methods that get "injected" into a class. They don't derive from it. So you could have a class like this (all code is in pseudo-code)
class RobotDog
implements interface IEat, IBark
implements mixin MEat, MBark
IEat and IBark provides the interfaces, while MEat and MBark would be the mixins with some default implementation that you could inject. A design like this is possible in JavaScript, but not currently in C#. It has the advantage that in the end you have a RobotDog class that has all methods of IEat and IBark with a shared implementation. And the this is also a disadvantage at the same time, because you create big classes with a lot of methods. On top of it there can be method conflicts. For example when you want to inject two different interfaces with the same name/signature. As good as such an approach looks first, i think the disadvantages are big and i wouldn't encourage such a design.
As C# doesn't support Mixins directly you could use Extension Methods to somehow rebuilt the design above. So you still have IEat and IBark interfaces. And you provide Extension Methods for the interfaces. But it has the same disadvantages as a mixin implementations. All methods appear on the object, problems with method names collision. Also on top, the idea of composition is also that you could provide different implementations. You also could have different Mixins for the same interface. And on top of it, mixins are just there for some kind of default implementation, the idea is still that you could overwrite or change a method.
Doing that kind of things with Extensions Method is possible but i wouldn't use such a design. You could theoretically create multiple different namespaces so depending on which namespace you load, you get different Extension Method with different implementation. But such a design feels more awkward to me. So i wouldn't use such a design.
The typical way how i would solve it, is by expecting fields for every behaviour you want. So your RobotDog looks like this
class RobotDog(ieat, ibark)
IEat Eat = ieat
IBark Bark = ibark
So this means. You have a class that contains two properties Eat and Bark. Those properties are of type IEat and IBark. If you want to create a RobotDog instance then you have to pass in a specific IEat and IBark implementation that you want to use.
let eat = new CatEat()
let bark = new DogBark()
let robotdog = new RobotDog(eat, bark)
Now RobotDog would Eat like a cat, and Bark like a Dog. You just can call what your RobotDog should do.
robotdog.Eat.Fruit()
robotdof.Eat.Drink()
robotdog.Bark.Loud()
Now the behaviour of your RobotDog completely depends on the injected objects that you provide while constructing your object. You also could switch the behaviour at runtime with another class. If your RobotDog is in a game and Barking gets upgraded you just could replace Bark at runtime with another object and the behaviour you want
robotdog.Bark <- new DeadlyScreamBarking()
Either way by mutating it, or creating a new object. You can use a mutable or immutable design, it is up to you. So you have code sharing. At least me i like the style a lot more, because instead of having a object with hundreds of methods you basically have a first layer with different objects that have each ability cleanly separated. If you for example add Moving to your RobotDog class you just could add a "IMovable" property and that interface could contain multiple methods like MoveTo, CalculatePath, Forward, SetSpeed and so on. They would be cleanly avaible under robotdog.Move.XYZ. You also have no problem with colliding methods. For example there could be methods with the same name on each class without any problem. And on top. You also can have multiple behaviours of the same type! For example Health and Shield could use the same type. For example a simple "MinMax" type that contains a min/max and current value and methods to operate on them. Health/Shield basically have the same behaviour, and you can easily use two of them in the same class with this approach because no method/property or event is colliding.
robotdog.Health.Increase(10)
robotdog.Shield.Increase(10)
The previous design could slightly be changed, but i don't think it makes it better. But a lot of people brainlessly adopt every design pattern or law with the hope it automatically makes everything better. What i want to refer here is the often called Law-of-Demeter that i think is awful, especially in this example. Actually there exists a lot of discussion of whether it is good or not. I think it is not a good rule to follow, and in that case it also becomes obvious. If you follow it you have to implement a method for every object that you have. So instead of
robotdog.Eat.Fruit()
robotdog.Eat.Drink()
you implement methods on RobotDog that calls some method on the Eat field, so with what did you end up?
robotdog.EatFruit()
robotdog.EatDrink()
You also need once again to solve collisions like
robotdog.IncreaseHealt(10)
robotdog.IncreaseShield(10)
Actually you just write a lot of methods that just delegates to some other methods on a field. But what did you won? Basically nothing at all. You just followed brainless a rule. You could theoretically say. But EatFruit() could do something different or do something additional before calling Eat.Fruit(). Weel yes that could be. But if you want other different Eat behaviour then you just create another class that implements IEat and you assign that class to the robotdog when you instantiate it.
In that sense, the Law of Demeter is not a dot counting Exercise.
http://haacked.com/archive/2009/07/14/law-of-demeter-dot-counting.aspx/
As a conclusion. If you follow that design i would consider using the third version. Use Properties that contain your Behaviour objects, and you can directly use those behaviours.

I think this is more of a conceptual dilemma rather than a composition issue.
When you say :
And implement it in the Dog and RobotDog classes
public class Dog : Animal, IBarkable
{
public void IBarkable.Bark() { Console.WriteLine("Bark"); }
}
public class RobotDog : Robot, IBarkable
{
public void IBarkable.Bark() { Console.WriteLine("Bark"); }
}
But once again we have duplicate code!
If Dog and RobotDog have the same Bark() implementation, they should inherit from the Animal class. But if their Bark() implementations are different, it makes sense to derive from IBarkable interface. Otherwise, where is the distinction between Dog and RobotDog?

Related

Noob question: in C# why would a user rely upon an empty method from an interface? [duplicate]

The reason for interfaces truly eludes me. From what I understand, it is kind of a work around for the non-existent multi-inheritance which doesn't exist in C# (or so I was told).
All I see is, you predefine some members and functions, which then have to be re-defined in the class again. Thus making the interface redundant. It just feels like syntactic… well, junk to me (Please no offense meant. Junk as in useless stuff).
In the example given below taken from a different C# interfaces thread on stack overflow, I would just create a base class called Pizza instead of an interface.
easy example (taken from a different stack overflow contribution)
public interface IPizza
{
public void Order();
}
public class PepperoniPizza : IPizza
{
public void Order()
{
//Order Pepperoni pizza
}
}
public class HawaiiPizza : IPizza
{
public void Order()
{
//Order HawaiiPizza
}
}
No one has really explained in plain terms how interfaces are useful, so I'm going to give it a shot (and steal an idea from Shamim's answer a bit).
Lets take the idea of a pizza ordering service. You can have multiple types of pizzas and a common action for each pizza is preparing the order in the system. Each pizza has to be prepared but each pizza is prepared differently. For example, when a stuffed crust pizza is ordered the system probably has to verify certain ingredients are available at the restaurant and set those aside that aren't needed for deep dish pizzas.
When writing this in code, technically you could just do
public class Pizza
{
public void Prepare(PizzaType tp)
{
switch (tp)
{
case PizzaType.StuffedCrust:
// prepare stuffed crust ingredients in system
break;
case PizzaType.DeepDish:
// prepare deep dish ingredients in system
break;
//.... etc.
}
}
}
However, deep dish pizzas (in C# terms) may require different properties to be set in the Prepare() method than stuffed crust, and thus you end up with a lot of optional properties, and the class doesn't scale well (what if you add new pizza types).
The proper way to solve this is to use interface. The interface declares that all Pizzas can be prepared, but each pizza can be prepared differently. So if you have the following interfaces:
public interface IPizza
{
void Prepare();
}
public class StuffedCrustPizza : IPizza
{
public void Prepare()
{
// Set settings in system for stuffed crust preparations
}
}
public class DeepDishPizza : IPizza
{
public void Prepare()
{
// Set settings in system for deep dish preparations
}
}
Now your order handling code does not need to know exactly what types of pizzas were ordered in order to handle the ingredients. It just has:
public PreparePizzas(IList<IPizza> pizzas)
{
foreach (IPizza pizza in pizzas)
pizza.Prepare();
}
Even though each type of pizza is prepared differently, this part of the code doesn't have to care what type of pizza we are dealing with, it just knows that it's being called for pizzas and therefore each call to Prepare will automatically prepare each pizza correctly based on its type, even if the collection has multiple types of pizzas.
The point is that the interface represents a contract. A set of public methods any implementing class has to have. Technically, the interface only governs syntax, i.e. what methods are there, what arguments they get and what they return. Usually they encapsulate semantics as well, although that only by documentation.
You can then have different implementations of an interface and swap them out at will. In your example, since every pizza instance is an IPizza you can use IPizza wherever you handle an instance of an unknown pizza type. Any instance whose type inherits from IPizza is guaranteed to be orderable, as it has an Order() method.
Python is not statically-typed, therefore types are kept and looked up at runtime. So you can try calling an Order() method on any object. The runtime is happy as long as the object has such a method and probably just shrugs and says »Meh.« if it doesn't. Not so in C#. The compiler is responsible for making the correct calls and if it just has some random object the compiler doesn't know yet whether the instance during runtime will have that method. From the compiler's point of view it's invalid since it cannot verify it. (You can do such things with reflection or the dynamic keyword, but that's going a bit far right now, I guess.)
Also note that an interface in the usual sense does not necessarily have to be a C# interface, it could be an abstract class as well or even a normal class (which can come in handy if all subclasses need to share some common code – in most cases, however, interface suffices).
For me, when starting out, the point to these only became clear when you stop looking at them as things to make your code easier/faster to write - this is not their purpose. They have a number of uses:
(This is going to lose the pizza analogy, as it's not very easy to visualise a use of this)
Say you are making a simple game on screen and It will have creatures with which you interact.
A: They can make your code easier to maintain in the future by introducing a loose coupling between your front end and your back end implementation.
You could write this to start with, as there are only going to be trolls:
// This is our back-end implementation of a troll
class Troll
{
void Walk(int distance)
{
//Implementation here
}
}
Front end:
function SpawnCreature()
{
Troll aTroll = new Troll();
aTroll.Walk(1);
}
Two weeks down the line, marketing decide you also need Orcs, as they read about them on twitter, so you would have to do something like:
class Orc
{
void Walk(int distance)
{
//Implementation (orcs are faster than trolls)
}
}
Front end:
void SpawnCreature(creatureType)
{
switch(creatureType)
{
case Orc:
Orc anOrc = new Orc();
anORc.Walk();
case Troll:
Troll aTroll = new Troll();
aTroll.Walk();
}
}
And you can see how this starts to get messy. You could use an interface here so that your front end would be written once and (here's the important bit) tested, and you can then plug in further back end items as required:
interface ICreature
{
void Walk(int distance)
}
public class Troll : ICreature
public class Orc : ICreature
//etc
Front end is then:
void SpawnCreature(creatureType)
{
ICreature creature;
switch(creatureType)
{
case Orc:
creature = new Orc();
case Troll:
creature = new Troll();
}
creature.Walk();
}
The front end now only cares about the interface ICreature - it's not bothered about the internal implementation of a troll or an orc, but only on the fact that they implement ICreature.
An important point to note when looking at this from this point of view is that you could also easily have used an abstract creature class, and from this perspective, this has the same effect.
And you could extract the creation out to a factory:
public class CreatureFactory {
public ICreature GetCreature(creatureType)
{
ICreature creature;
switch(creatureType)
{
case Orc:
creature = new Orc();
case Troll:
creature = new Troll();
}
return creature;
}
}
And our front end would then become:
CreatureFactory _factory;
void SpawnCreature(creatureType)
{
ICreature creature = _factory.GetCreature(creatureType);
creature.Walk();
}
The front end now does not even have to have a reference to the library where Troll and Orc are implemented (providing the factory is in a separate library) - it need know nothing about them whatsoever.
B: Say you have functionality that only some creatures will have in your otherwise homogenous data structure, e.g.
interface ICanTurnToStone
{
void TurnToStone();
}
public class Troll: ICreature, ICanTurnToStone
Front end could then be:
void SpawnCreatureInSunlight(creatureType)
{
ICreature creature = _factory.GetCreature(creatureType);
creature.Walk();
if (creature is ICanTurnToStone)
{
(ICanTurnToStone)creature.TurnToStone();
}
}
C: Usage for dependency injection
Most dependency injection frameworks work when there is a very loose coupling between the front end code and the back end implementation. If we take our factory example above and have our factory implement an interface:
public interface ICreatureFactory {
ICreature GetCreature(string creatureType);
}
Our front end could then have this injected (e.g an MVC API controller) through the constructor (typically):
public class CreatureController : Controller {
private readonly ICreatureFactory _factory;
public CreatureController(ICreatureFactory factory) {
_factory = factory;
}
public HttpResponseMessage TurnToStone(string creatureType) {
ICreature creature = _factory.GetCreature(creatureType);
creature.TurnToStone();
return Request.CreateResponse(HttpStatusCode.OK);
}
}
With our DI framework (e.g. Ninject or Autofac), we can set them up so that at runtime a instance of CreatureFactory will be created whenever an ICreatureFactory is needed in an constructor - this makes our code nice and simple.
It also means that when we write a unit test for our controller, we can provide a mocked ICreatureFactory (e.g. if the concrete implementation required DB access, we don't want our unit tests dependent on that) and easily test the code in our controller.
D: There are other uses e.g. you have two projects A and B that for 'legacy' reasons are not well structured, and A has a reference to B.
You then find functionality in B that needs to call a method already in A. You can't do it using concrete implementations as you get a circular reference.
You can have an interface declared in B that the class in A then implements. Your method in B can be passed an instance of a class that implements the interface with no problem, even though the concrete object is of a type in A.
Examples above don't make much sense. You could accomplish all above examples using classes (abstract class if you want it to behave only as a contract):
public abstract class Food {
public abstract void Prepare();
}
public class Pizza : Food {
public override void Prepare() { /* Prepare pizza */ }
}
public class Burger : Food {
public override void Prepare() { /* Prepare Burger */ }
}
You get the same behavior as with interface. You can create a List<Food> and iterate that w/o knowing what class sits on top.
More adequate example would be multiple inheritance:
public abstract class MenuItem {
public string Name { get; set; }
public abstract void BringToTable();
}
// Notice Soda only inherits from MenuItem
public class Soda : MenuItem {
public override void BringToTable() { /* Bring soda to table */ }
}
// All food needs to be cooked (real food) so we add this
// feature to all food menu items
public interface IFood {
void Cook();
}
public class Pizza : MenuItem, IFood {
public override void BringToTable() { /* Bring pizza to table */ }
public void Cook() { /* Cook Pizza */ }
}
public class Burger : MenuItem, IFood {
public override void BringToTable() { /* Bring burger to table */ }
public void Cook() { /* Cook Burger */ }
}
Then you can use all of them as MenuItem and don't care about how they handle each method call.
public class Waiter {
public void TakeOrder(IEnumerable<MenuItem> order)
{
// Cook first
// (all except soda because soda is not IFood)
foreach (var food in order.OfType<IFood>())
food.Cook();
// Bring them all to the table
// (everything, including soda, pizza and burger because they're all menu items)
foreach (var menuItem in order)
menuItem.BringToTable();
}
}
Simple Explanation with analogy
No interface (Example 1):
No interface (Example 2):
With an interface:
The Problem to Solve: What is the purpose of polymorphism?
Analogy: So I'm a foreperson on a construction site. I don't know which tradesperson is going to walk in. But I tell them what to do.
If it's a carpenter I say: build wooden scaffolding.
If it's a plumber, I say: Set up the pipes
If it's a BJP government bureaucrat, I say, three bags full of cash, sir.
The problem with the above approach is that I have to: (i) know who's walking in that door, and depending on who it is, I have to tell them what to do. This typically makes code harder to maintain or more error prone.
The implications of knowing what to do:
This means if the carpenter's code changes from: BuildScaffolding() to BuildScaffold() (i.e. a slight name change) then I will have to also change the calling class (i.e. the Foreperson class) as well - you'll have to make two changes to the code instead of (basically) just one. With polymorphism you (basically) only need to make one change to achieve the same result.
Secondly you won't have to constantly ask: who are you? ok do this...who are you? ok do that.....polymorphism - it DRYs that code, and is very effective in certain situations:
with polymorphism you can easily add additional classes of tradespeople without changing any existing code. (i.e. the second of the SOLID design principles: Open-close principle).
The solution
Imagine a scenario where, no matter who walks in the door, I can say: "Work()" and they do their respect jobs that they specialise in: the plumber would deal with pipes, and the electrician would deal with wires, and a bureaucrat could specialise in extracting bribes and making double work for everyone else.
The benefit of this approach is that: (i) I don't need to know exactly who is walking in through that door - all i need to know is that they will be a type of tradie and that they can do work, and secondly, (ii) i don't need to know anything about that particular trade. The tradie will take care of that.
So instead of this:
if(electrician) then electrician.FixCablesAndElectricity()
if(plumber) then plumber.IncreaseWaterPressureAndFixLeaks()
if(keralaCustoms) then keralaCustoms.askForBribes()
I can do something like this:
ITradesman tradie = Tradesman.Factory(); // in reality i know it's a plumber, but in the real world you won't know who's on the other side of the tradie assignment.
tradie.Work(); // and then tradie will do the work of a plumber, or electrician etc. depending on what type of tradesman he is. The foreman doesn't need to know anything, apart from telling the anonymous tradie to get to Work()!!
What's the benefit?
The benefit is that if the specific job requirements of the carpenter etc change, then the foreperson won't need to change his code - he doesn't need to know or care. All that matters is that the carpenter knows what is meant by Work(). Secondly, if a new type of construction worker comes onto the job site, then the foreman doesn't need to know anything about the trade - all the foreman cares is if the construction worker (.e.g Welder, Glazier, Tiler etc.) can get some Work() done.
Summary
An interface allows you to get the person to do the work they are assigned to, without you having the knowledge of exactly who they are or the specifics of what they can do. This allows you to easily add new types (of trade) without changing your existing code (well technically you do change it a tiny tiny bit), and that's the real benefit of an OOP approach vs. a more functional programming methodology.
If you don't understand any of the above or if it isn't clear ask in a comment and i'll try to make the answer better.
Here are your examples reexplained:
public interface IFood // not Pizza
{
public void Prepare();
}
public class Pizza : IFood
{
public void Prepare() // Not order for explanations sake
{
//Prepare Pizza
}
}
public class Burger : IFood
{
public void Prepare()
{
//Prepare Burger
}
}
In the absence of duck typing as you can use it in Python, C# relies on interfaces to provide abstractions. If the dependencies of a class were all concrete types, you could not pass in any other type - using interfaces you can pass in any type that implements the interface.
The Pizza example is bad because you should be using an abstract class that handles the ordering, and the pizzas should just override the pizza type, for example.
You use interfaces when you have a shared property, but your classes inherit from different places, or when you don't have any common code you could use. For instance, this is used things that can be disposed IDisposable, you know it will be disposed, you just don't know what will happen when it's disposed.
An interface is just a contract that tells you some things an object can do, what parameters and what return types to expect.
Consider the case where you don't control or own the base classes.
Take visual controls for instance, in .NET for Winforms they all inherit from the base class Control, that is completely defined in the .NET framework.
Let's assume you're in the business of creating custom controls. You want to build new buttons, textboxes, listviews, grids, whatnot and you'd like them all to have certain features unique to your set of controls.
For instance you might want a common way to handle theming, or a common way to handle localization.
In this case you can't "just create a base class" because if you do that, you have to reimplement everything that relates to controls.
Instead you will descend from Button, TextBox, ListView, GridView, etc. and add your code.
But this poses a problem, how can you now identify which controls are "yours", how can you build some code that says "for all the controls on the form that are mine, set the theme to X".
Enter interfaces.
Interfaces are a way to look at an object, to determine that the object adheres to a certain contract.
You would create "YourButton", descend from Button, and add support for all the interfaces you need.
This would allow you to write code like the following:
foreach (Control ctrl in Controls)
{
if (ctrl is IMyThemableControl)
((IMyThemableControl)ctrl).SetTheme(newTheme);
}
This would not be possible without interfaces, instead you would have to write code like this:
foreach (Control ctrl in Controls)
{
if (ctrl is MyThemableButton)
((MyThemableButton)ctrl).SetTheme(newTheme);
else if (ctrl is MyThemableTextBox)
((MyThemableTextBox)ctrl).SetTheme(newTheme);
else if (ctrl is MyThemableGridView)
((MyThemableGridView)ctrl).SetTheme(newTheme);
else ....
}
In this case, you could ( and probably would ) just define a Pizza base class and inherit from them. However, there are two reasons where Interfaces allow you to do things that cannot be achieved in other ways:
A class can implement multiple interfaces. It just defines features that the class must have. Implementing a range of interfaces means that a class can fulfil multiple functions in different places.
An interface can be defined in a hogher scope than the class or the caller. This means that you can separate the functionality, separate the project dependency, and keep the functionality in one project or class, and the implementation of this elsewhere.
One implication of 2 is that you can change the class that is being used, just requiring that it implements the appropriate interface.
Consider you can't use multiple inheritance in C#, and then look at your question again.
I did a search for the word "composition" on this page and didn't see it once. This answer is very much in addition to the answers aforementioned.
One of the absolutely crucial reasons for using interfaces in an Object Oriented Project is that they allow you to favour composition over inheritance. By implementing interfaces you can decouple your implementations from the various algorithms you are applying to them.
This superb "Decorator Pattern" tutorial by Derek Banas (which - funnily enough - also uses pizza as an example) is a worthwhile illustration:
https://www.youtube.com/watch?v=j40kRwSm4VE
Interface = contract, used for loose coupling (see GRASP).
If I am working on an API to draw shapes, I may want to use DirectX or graphic calls, or OpenGL. So, I will create an interface, which will abstract my implementation from what you call.
So you call a factory method: MyInterface i = MyGraphics.getInstance(). Then, you have a contract, so you know what functions you can expect in MyInterface. So, you can call i.drawRectangle or i.drawCube and know that if you swap one library out for another, that the functions are supported.
This becomes more important if you are using Dependency Injection, as then you can, in an XML file, swap implementations out.
So, you may have one crypto library that can be exported that is for general use, and another that is for sale only to American companies, and the difference is in that you change a config file, and the rest of the program isn't changed.
This is used a great deal with collections in .NET, as you should just use, for example, List variables, and don't worry whether it was an ArrayList or LinkedList.
As long as you code to the interface then the developer can change the actual implementation and the rest of the program is left unchanged.
This is also useful when unit testing, as you can mock out entire interfaces, so, I don't have to go to a database, but to a mocked out implementation that just returns static data, so I can test my method without worrying if the database is down for maintenance or not.
Interfaces are for applying connection between different classes. for example, you have a class for car and a tree;
public class Car { ... }
public class Tree { ... }
you want to add a burnable functionality for both classes. But each class have their own ways to burn. so you simply make;
public class Car : IBurnable
{
public void Burn() { ... }
}
public class Tree : IBurnable
{
public void Burn() { ... }
}
You will get interfaces, when you will need them :) You can study examples, but you need the Aha! effect to really get them.
Now that you know what interfaces are, just code without them. Sooner or later you will run into a problem, where the use of interfaces will be the most natural thing to do.
An interface is really a contract that the implementing classes must follow, it is in fact the base for pretty much every design pattern I know.
In your example, the interface is created because then anything that IS A Pizza, which means implements the Pizza interface, is guaranteed to have implemented
public void Order();
After your mentioned code you could have something like this:
public void orderMyPizza(IPizza myPizza) {
//This will always work, because everyone MUST implement order
myPizza.order();
}
This way you are using polymorphism and all you care is that your objects respond to order().
I'm surprised that not many posts contain the one most important reason for an interface: Design Patterns. It's the bigger picture into using contracts, and although it's a syntax decoration to machine code (to be honest, the compiler probably just ignores them), abstraction and interfaces are pivotal for OOP, human understanding, and complex system architectures.
Let's expand the pizza analogy to say a full fledge 3 course meal. We'll still have the core Prepare() interface for all our food categories, but we'd also have abstract declarations for course selections (starter, main, dessert), and differing properties for food types (savoury/sweet, vegetarian/non-vegetarian, gluten free etc).
Based on these specifications, we could implement the Abstract Factory pattern to conceptualise the whole process, but use interfaces to ensure that only the foundations were concrete. Everything else could become flexible or encourage polymorphism, yet maintain encapsulation between the different classes of Course that implement the ICourse interface.
If I had more time, I'd like to draw up a full example of this, or someone can extend this for me, but in summary, a C# interface would be the best tool in designing this type of system.
Here's an interface for objects that have a rectangular shape:
interface IRectangular
{
Int32 Width();
Int32 Height();
}
All it demands is that you implement ways to access the width and height of the object.
Now let's define a method that will work on any object that is IRectangular:
static class Utils
{
public static Int32 Area(IRectangular rect)
{
return rect.Width() * rect.Height();
}
}
That will return the area of any rectangular object.
Let's implement a class SwimmingPool that is rectangular:
class SwimmingPool : IRectangular
{
int width;
int height;
public SwimmingPool(int w, int h)
{ width = w; height = h; }
public int Width() { return width; }
public int Height() { return height; }
}
And another class House that is also rectangular:
class House : IRectangular
{
int width;
int height;
public House(int w, int h)
{ width = w; height = h; }
public int Width() { return width; }
public int Height() { return height; }
}
Given that, you can call the Area method on houses or swimming-pools:
var house = new House(2, 3);
var pool = new SwimmingPool(3, 4);
Console.WriteLine(Utils.Area(house));
Console.WriteLine(Utils.Area(pool));
In this way, your classes can "inherit" behavior (static-methods) from any number of interfaces.
What ?
Interfaces are basically a contract that all the classes implementing the Interface should follow. They looks like a class but has no implementation.
In C# Interface names by convention is defined by Prefixing an 'I' so if you want to have an interface called shapes, you would declare it as IShapes
Now Why ?
Improves code re-usability
Lets say you want to draw Circle, Triangle.
You can group them together and call them Shapesand have methods to draw Circle and Triangle
But having concrete implementation would be a bad idea because tomorrow you might decide to have 2 more Shapes Rectangle & Square. Now when you add them there is a great chance that you might break other parts of your code.
With Interface you isolate the different implementation from the Contract
Live Scenario Day 1
You were asked to create an App to Draw Circle and Triangle
interface IShapes
{
void DrawShape();
}
class Circle : IShapes
{
public void DrawShape()
{
Console.WriteLine("Implementation to Draw a Circle");
}
}
Class Triangle: IShapes
{
public void DrawShape()
{
Console.WriteLine("Implementation to draw a Triangle");
}
}
static void Main()
{
List <IShapes> shapes = new List<IShapes>();
shapes.Add(new Circle());
shapes.Add(new Triangle());
foreach(var shape in shapes)
{
shape.DrawShape();
}
}
Live Scenario Day 2
If you were asked add Square and Rectangle to it, all you have to do is create the implentation for it in class Square: IShapes and in Main add to list shapes.Add(new Square());
An interface defines a contract between the provider of a certain functionality and the correspondig consumers. It decouples the implementation from the contract (interface). You should have a look at object oriented architecture and design. You may want to start with wikipedia: http://en.wikipedia.org/wiki/Interface_(computing)
There are a lot of good answers here but I would like to try from a slightlt different perspective.
You may be familiar with the SOLID principles of object oriented design. In summary:
S - Single Responsibility Principle
O - Open/Closed Principle
L - Liskov Substitution Principle
I - Interface Segregation Principle
D - Dependency Inversion Principle
Following the SOLID principles helps to produce code that is clean, well factored, cohesive and loosely coupled. Given that:
"Dependency management is the key challenge in software at every scale" (Donald Knuth)
then anything that helps with dependency management is a big win. Interfaces and the Dependency Inversion Principle really help to decouple code from dependencies on concrete classes, so code can be written and reasoned about in terms of behaviours rather than implementations. This helps to break the code into components which can be composed at runtime rather than compile time and also means those components can be quite easily plugged in and out without having to alter the rest of the code.
Interfaces help in particular with the Dependency Inversion Principle, where code can be componentized into a collection of services, with each service being described by an interface. Services can then be "injected" into classes at runtime by passing them in as a constructor parameter. This technique really becomes critical if you start to write unit tests and use test driven development. Try it! You will quickly understand how interfaces help to break apart the code into manageable chunks that can be individually tested in isolation.
Soo many answers!
Giving my best shot. hehe.
So to begin, yes you could have used a concrete base and derived class here. In that case, you would have to do an empty or useless implementation for the Prepare method in the base class also making this method virtual and then the derived classes would override this Prepare method for themselves. This case, the implementation of Prepare in Base class is useless.
The reason why you chose to use an Interface is because you had to define a contract, not an implementation.
There is a IPizza type and it provides a functionality to Prepare. This is contract. How it is prepared is the implementation and it is not your lookout. It is responsibility of the various Pizza implementations.
An interface or an abstract class is preferred here over a concrete base class because you had to create an abstraction, i.e., the Prepare method. You cannot create an abstract method in a concrete base class.
Now you could say, why not use an abstract class?
So, when you need to achieve 100% abstraction, you need to go with Interface. But when you need some abstraction along with a concrete implementation, go with abstract class. It means.
Example: Lets say all your pizzas will have a base and base preparation will be the same process. However, all pizza types and toppings will vary. In this case you could create an Abstract class with an abstract method Prepare and a concrete method PreparePizzaBase.
public abstract class Pizza{
// concrete method which is common to all pizzas.
public PizzaBase PreparePizzaBase(){
// code for pizza base preparation.
}
public abstract void Prepare();
}
public class DeluxePizza: Pizza{
public void Prepare(){
var base=PreparePizzaBase();
// prepare deluxe pizza on pizza base.
}
}
The main purpose of the interfaces is that it makes a contract between you and any other class that implement that interface which makes your code decoupled and allows expandability.
Therese are ask really great examples.
Another, in the case of a switch statement, you no longer have the need to maintain and switch every time you want rio perform a task in a specific way.
In your pizza example, if want to make a pizza, the interface is all you need, from there each pizza takes care of it's own logic.
This helps to reduce coupling and cyclomatic complexity. You have to still implement the logic but there will be less you have to keep track of in the broader picture.
For each pizza you can then keep track of information specific to that pizza. What other pizzas have doesn't matter because only the other pizzas need to know.
The simplest way to think about interfaces is to recognize what inheritance means. If class CC inherits class C, it means both that:
Class CC can use any public or protected members of class C as though they were its own, and thus only needs to implement things which do not exist in the parent class.
A reference to a CC can be passed or assigned to a routine or variable that expects a reference to a C.
Those two function of inheritance are in some sense independent; although inheritance applies both simultaneously, it is also possible to apply the second without the first. This is useful because allowing an object to inherit members from two or more unrelated classes is much more complicated than allowing one type of thing to be substitutable for multiple types.
An interface is somewhat like an abstract base class, but with a key difference: an object which inherits a base class cannot inherit any other class. By contrast, an object may implement an interface without affecting its ability to inherit any desired class or implement any other interfaces.
One nice feature of this (underutilized in the .net framework, IMHO) is that they make it possible to indicate declaratively the things an object can do. Some objects, for example, will want data-source object from which they can retrieve things by index (as is possible with a List), but they won't need to store anything there. Other routines will need a data-depository object where they can store things not by index (as with Collection.Add), but they won't need to read anything back. Some data types will allow access by index, but won't allow writing; others will allow writing, but won't allow access by index. Some, of course, will allow both.
If ReadableByIndex and Appendable were unrelated base classes, it would be impossible to define a type which could be passed both to things expecting a ReadableByIndex and things expecting an Appendable. One could try to mitigate this by having ReadableByIndex or Appendable derive from the other; the derived class would have to make available public members for both purposes, but warn that some public members might not actually work. Some of Microsoft's classes and interfaces do that, but that's rather icky. A cleaner approach is to have interfaces for the different purposes, and then have objects implement interfaces for the things they can actually do. If one had an interface IReadableByIndex and another interface IAppendable, classes which could do one or the other could implement the appropriate interfaces for the things they can do.
Interfaces can also be daisy chained to create yet another interface. This ability to implement multiple Interfaces give the developer the advantage of adding functionality to their classes without having to change current class functionality (SOLID Principles)
O = "Classes should be open for extension but closed for modification"
To me an advantage/benefit of an interface is that it is more flexible than an abstract class. Since you can only inherit 1 abstract class but you can implement multiple interfaces, changes to a system that inherits an abstract class in many places becomes problematic. If it is inherited in 100 places, a change requires changes to all 100. But, with the interface, you can place the new change in a new interface and just use that interface where its needed (Interface Seq. from SOLID). Additionally, the memory usage seems like it would be less with the interface as an object in the interface example is used just once in memory despite how many places implement the interface.
Interfaces are used to drive consistency,in a manner that is loosely coupled which makes it different to abstract class which is tightly coupled.That's why its also commonly defined as a contract.Whichever classes that implements the interface has abide to "rules/syntax" defined by the interface and there is no concrete elements within it.
I'll just give an example supported by the graphic below.
Imagine in a factory there are 3 types of machines.A rectangle machine,a triangle machine and a polygon machine.Times are competitive and you want to streamline operator training.You just want to train them in one methodology of starting and stopping machines so you have a green start button and red stop button.So now across 3 different machines you have a consistent way of starting and stopping 3 different types of machines.Now imagine these machines are classes and the classes need to have start and stop methods,how you going to drive consistency across these classes which can be very different? Interface is the answer.
A simple example to help you visualize,one might ask why not use abstract class? With an interface the objects don't have to be directly related or inherited and you can still drive consistency across different classes.
public interface IMachine
{
bool Start();
bool Stop();
}
public class Car : IMachine
{
public bool Start()
{
Console.WriteLine("Car started");
return true;
}
public bool Stop()
{
Console.WriteLine("Car stopped");
return false;
}
}
public class Tank : IMachine
{
public bool Start()
{
Console.WriteLine("Tank started");
return true;
}
public bool Stop()
{
Console.WriteLine("Tank stopped");
return false;
}
}
class Program
{
static void Main(string[] args)
{
var car = new Car();
car.Start();
car.Stop();
var tank = new Tank();
tank.Start();
tank.Stop();
}
}
class Program {
static void Main(string[] args) {
IMachine machine = new Machine();
machine.Run();
Console.ReadKey();
}
}
class Machine : IMachine {
private void Run() {
Console.WriteLine("Running...");
}
void IMachine.Run() => Run();
}
interface IMachine
{
void Run();
}
Let me describe this by a different perspective. Let’s create a story according to the example which i have shown above;
Program, Machine and IMachine are the actors of our story. Program wants to run but it has not that ability and Machine knows how to run. Machine and IMachine are best friends but Program is not on speaking terms with Machine. So Program and IMachine make a deal and decided that IMachine will tell to Program how to run by looking Machine(like a reflector).
And Program learns how to run by help of IMachine.
Interface provides communication and developing loosely coupled projects.
PS: I’ve the method of concrete class as private. My aim in here is to achieve loosely coupled by preventing accessing concrete class properties and methods, and left only allowing way to reach them via interfaces. (So i defined interfaces’ methods explicitily).

What to use here, abstract class or Interface? [duplicate]

This question already has answers here:
When to use an interface instead of an abstract class and vice versa?
(26 answers)
Closed 8 years ago.
I have an abstract class say CTest which contains only the abstract method f1() and nothing else. Similiarly, i have a Interface ITest with the only method f1(). Here both the CTest abstract class and ITest interface does the same thing.
The one difference is that, the Interface provides the flexibility that it can be implemented in any classes which already derived from other class but abstract classes cannot.
Apart from the above difference, What is the actual difference between these two? and which one is efficient here(CTest or ITest)? When i should use what? Any specific scenario's in OO Design and any general suggessions on this are helpful
Other than inheritance, it depends on the scenario. Check this code project article with an excellent example.
[From the article]
Lets Assume you need to make three classes, first is CAR, second is
MAN, third is WOMAN. Now you need a function in each of them to define
how they Move. Now all three can move but CAR moves entirely in
different way than MAN and WOMAN. So here we use an Interface
IMOVEMENT and declare a function MOVE in it. Now all three classes can
inherit this interface. So the classes goes like this.
public interface IMovement
{
void Move();
}
public class Car : IMovement
{
public void Move()
{
//Provide Implementation
}
}
public class Man : IMovement
{
public void Move()
{
//Provide Implementation
}
}
public class Woman : IMovement
{
public void Move()
{
//Provide Implementation
}
}
But, since MAN and WOMAN walk in similar way, so providing same
behavior in two different methods will be code redundancy, in simpler
words code is not re-used. So we can now define a Abstract Class for
Human Beings movements, so this class can be HUMANBEINGMOVEMENT. Also
the same can be applied to CAR class, since there are lot of
manufactures for cars and all cars move in similar way so we can also
define a abstract class for Cars movement which can be CARSMOVEMENT.
So our refactored code will be .
public interface IMovement
{
void Move();
}
public abstract class CarsMovement : IMovement
{
public virtual void Move()
{
//default behavior for cars movement
}
}
public class SuzukiCar : CarsMovement
{
public override void Move()
{
//Provide Implementation
}
}
public abstract class HumanBeingMovement : IMovement
{
public virtual void Move()
{
//default behavior for human being movement
}
}
public class Man : HumanBeingMovement
{
public override void Move()
{
//Provide Implementation
}
}
public class Woman : HumanBeingMovement
{
public override void Move()
{
//Provide Implementation
}
}
In Java prefer Interfaces to Abstract Classes. Refer Item 18 in Effective Java
Main Points :
Existing classes can be retroffited to implement a new interface.
Interfaces are ideal for defining mixins.
Interfaces allow the construction of nonheirarchical type frameworks.
Interfaces enable safe, powerful functionality enhancements.
in c# it allows only single level inheritance. therefore interfaces can be use to do multiple inheritances
and also for more details :
http://www.dotnetfunda.com/forums/thread4085-difference-between-interface-and-abstract-class.aspx
http://sadi02.wordpress.com/2008/05/08/what-is-difference-in-an-abstract-class-and-an-interface/
For me it better to use interface here. Abstract class should be used when you could extract some code there (you could implement method or there is other stuff that want to invoke it).
In this case there is no difference but CTest class has the only class which could be inherited as a Class . However ITest interface can be inherited by other class and interface at the same time.
In the scenario you have mentioned, that there is only one method, which will have no definition, the best way to go for is interface.
The major advantage an interface gives in Java that you can implement more than one interfaces, but you can extend only one class. So if you are already extending the one abstract class, you are not left with an option of extending any other class.
Golden rule: Interface is better than abstract class if we only need
to define methods and not declare them.
Having said that an interface is better in your case, a programmer should also think of his code from a future perspective. Do you feel the class/ interface you are creating will have more methods in future. Would you like to define those methods or just declare? Answer to these question will let you know if an interface is sufficient or will need an abstract class.
Advantage:
Implementation of Abstract class is better than Interface because method looking up of abstract class is fast than interface. If you modify your interface , you have to update your implementation class but any modification of abstract class , no effect on implementation class.
disadvantage:
If you want to implement more than one parent class method , it is not possible.
But regarding to interface you can implement more than one.
In this case, and assuming that your Abstract Class will only contain abstract methods, you should, in my opinion, go with the Interface. Abstract classes with abstract methods and interfaces serve the same purpose, however, you can extend only one class but implement as many as you want, thus making your code less prone to significant changes should you decide the inherit some functionality from some other class.
Regarding your question: But What is the actual difference between these two? and which one is efficient here(CTest or ITest)? When i should use what? Any specific scenario's in OO Design and any general suggessions on this are helpful
Interfaces are similar to contracts, when a class implements an interface, it guarantees an implementation. This is usually helpful when someone wants to provide functionality but does not want to reveal internal code, so the developer will just throw out the interface so that you can make your calls without knowing how is each method implemented. You can obviously implement as many interfaces as you like.
Abstract classes allow you to create a class which has certain behaviours which are specified and some others which are left to be implemented in the future. Unlike interfaces however, each class can only extend one class, so you should extend classes with caution from this point of view. Abstract classes also allow you to inject behaviour to one class and have it automatically spread through its child classes. This usually makes certain sections of development/maintenance easier.

Interfaces vs. inheritance: which is better in this case?

Let's suppose I have a widget class:
struct Widget {
public Color Color { get; set; }
public int Frobbles { get; set; }
}
Now, I need to make a factory to create these widgets, so I build a WidgetFactory:
abstract class WidgetFactory {
public virtual Widget GetWidget();
}
As it turns out, you can make widgets out of several different materials, but the resulting widgets are pretty much the same. So, I have a few implementations of WidgetFactory:
class GoldWidgetFactory : WidgetFactory {
public GoldWidgetFactory(GoldMine goldmine) {
//...
}
public Widget GetWidget() {
Gold g = goldmine.getGold();
//...
}
}
class XMLWidgetFactory : WidgetFactory {
public XMLWidgetFactory(XmlDocument xmlsource) {
//...
}
public Widget GetWidget() {
XmlNode node = //whatever
//...
}
}
class MagicWidgetFactory : WidgetFactory {
public Widget GetWidget() {
//creates widget from nothing
}
}
My question is this: Should WidgetFactory be an abstract class, or an interface? I can see arguments in both directions:
Base class:
The implementations ARE WidgetFactories
They might be able to share functionality, (say, a List<Widget> WidgetFactory.GetAllWidgets() method)
Interface:
The implementations do not inherit any data or functionality from the parent
Their internal workings are completely different
Only one method is defined
To those answering, this does not (currently) parallel to any real-world problem, but if/when I need to implement this pattern, it would be good to know. Also, "it doesn't matter" is a valid answer.
Edit: I should point out why go through this in the first place. The hypothetical usage of this class hierarchy would be something like:
//create a widget factory
WidgetFactory factory = new GoldWidgetFactory(myGoldMine);
//get a widget for our own nefarious purposes
Widget widget = factory.GetWidget();
//this method needs a few widgets
ConsumeWidgets(factory);
So, having a GetGoldWidget() method in WidgetFactory is not a very good idea. Plus, perhaps advents in Widget technology allow us to add different and more exotic types of widgets in the future? It's easier and cleaner to add a new class to handle them than shoehorn a method into an existing class.
In the example that you have given WidgetFactory has absolutely no reason to be an abstract class since there are not shared attributes or methods between different implementations of the factory.
Even if there was shared functionality, it would be more idiomatic to make an interface and pass it around to the users of WidgetFactory, to reduce the mount of knowledge those components need to have about the factory.
The overall implementation is fine and is really an abstract factory pattern, the only addition I would do is IWidgetFactory:
public interface IWidgetFactory {
Widget GetWidget();
}
abstract class WidgetFactory : IWidgetFactory {
//common attributes and methods
}
//Defferent implementations can still inherit from the base abstract class
class GoldWidgetFactory : WidgetFactory {
public GoldWidgetFactory(GoldMine goldmine) {
//...
}
public Widget GetWidget() {
Gold g = goldmine.getGold();
//...
}
}
In this case I see no benefit to using an abstract class instead of an interface.
I would generally favour interfaces over abstract classes:
They don't use up your one opportunity at class inheritance
They can be easier to mock
They feel "purer" somehow (it's clear just from the interface what the implementer needs to provide; you don't need to check each method to see whether or not it's concrete, abstract, or virtual)
In this case, however, you could easily use a delegate as there's only a single method... basically a Func<Widget>.
I disagree with Larry's idea of just using a single factory to directly create all the widgets with separate methods - as you may want to pass the WidgetFactory as a dependency to another class which doesn't need to know about the source, but needs to call CreateWidget either at a different time or possibly multiple times.
However, you could have a single widget factory with multiple methods each returning a Func<Widget>. That would give the benefits of having a single factory class while also allowing for dependency injection of the "factory" notion.
Honestly, what ever else, besides the Concrete Factory classes, do you expect to inherit from WidgetFactory? Anything?... ever?
If not it probably doesn't ever matter.
If down the road you want to add common code between them all than an abstract class would be your best bet.
Also I don't really see the need for your factory methods to implement any other interface except that of your creation method. So it doesn't matter whether it's abstract or interface. It all comes down to whether in the future you will want to add additional functionality in the future to the abstract class.
You don't need inheritance or an interface or even more than one class. The single factory should make all different kinds of widgets ; you can just pass in the materials as a parameter to the create method. The idea is to hide the aspects of different construction of objects from the caller - by making a bunch of different classes you are exposing this, not hiding it.

'abstract class' versus 'normal class' for a reusable library

I'm developing a reusable library and have been creating abstract classes, so the client can then extend from these.
QUESTION: Is there any reason in fact I should use an abstract class here as opposed to just a normal class?
Note - Have already decided I do not want to use interfaces as I want to include actual default methods in my library so the client using it doesn't have to write the code.
EDIT: So I'm fishing for any advantages I can't think of. For example when upgrading the library would use of an abstract class lessen impact on client code - I can't see it would in this case no?
Unless you want to force the end users to inherit from your classes, there should be no reason to use abstract.
If you want to make your classes inheritable and easily extensible, use virtual on your methods and make sure you have usable protected constructors.
The motivation for the abstract class is to require clients to override the class. Your decision on whether the class should be abstract or not depends primarily on whether the abstract is missing some fundamental behavior that only an user of the class can supply.
You can usually tell you need your class to be abstract if you use a template method of some sort, where "plug in the hole in this behavior" completes the logic of he class. If your class is useful without some user-supplied logic, you probably don't need the class to be abstract.
As an example, frameworks usually can't make decisions on behalf of their users in terms of things like object state validation, printing, display, and so on, and they would need to defer to concrete implementations by the clients.
The difference between an abstract class and a non-abstract one is that you can't instantiate the former and it MUST be overriden. It is really up to you to determine whether or not an instance of the base class makes sense on its own.
Let me show you two cases. One is where abstract class makes sense and one where it doesn't.
public abstract class Animal {
public string Name {get;set;}
}
public class Dog : Animal {
public Bark(){}
}
public class Cat : Animal {
public Meaow(){}
}
In this scenario we have a common base Animal that provides implementation for Name property. It makes no sense to instantiate Animal by itself as there are no animals in the world that are just animals, they are wither dogs or cats or something else.
Here is a case where it makes sense to have a non-abstract base.
class Path {
public Path(IList<Point> points) {
this.Points = new ReadOnlyCollection<Point>(points);
}
public ReadOnlyCollection<Point> Points {get;}
}
class RectanglePath : Path{
public SquarePath (Point origin, int height, int width) :
base(new List<Point>{origin, new Point(origin.X + width, point.Y}, ....){
}
}
Here Path that is not subclassed makes sense, we can create any arbitrary shape, but it might be more convenient to use a sublass for more specific shapes.
Sounds like you are a little confused about the difference between a virtual method and an abstract class. You don't need to mark your class as abstract unless you determine that it doesn't make sense on it's own. This is useful in areas where you might have shared behaviors between multiple classes.
Sounds to me like you just need a regular class and some methods that are virtual.

C# - Interface -Help in power of Interface

I am new to C#. Recently I have read an article.It suggests
"One of the practical uses of interface is, when an interface reference is created that can
work on different kinds of objects which implements that interface."
Base on that I tested (I am not sure my understanding is correct)
namespace InterfaceExample
{
public interface IRide
{
void Ride();
}
abstract class Animal
{
private string _classification;
public string Classification
{
set { _classification = value;}
get { return _classification;}
}
public Animal(){}
public Animal(string _classification)
{
this._classification = _classification;
}
}
class Elephant:Animal,IRide
{
public Elephant(){}
public Elephant(string _majorClass):base(_majorClass)
{
}
public void Ride()
{
Console.WriteLine("Elephant can ride 34KPM");
}
}
class Horse:Animal,IRide
{
public Horse(){}
public Horse(string _majorClass):base(_majorClass)
{
}
public void Ride()
{
Console.WriteLine("Horse can ride 110 KPH");
}
}
class Test
{
static void Main()
{
Elephant bully = new Elephant("Vertebrata");
Horse lina = new Horse("Vertebrata");
IRide[] riders = {bully,lina};
foreach(IRide rider in riders)
{
rider.Ride();
}
Console.ReadKey(true);
}
}
}
Questions :
Beyond such extend, what are the different way can we leverage the elegance of Interfaces ?
What is the Key point that I can say this can be only done by interface (apart from
multiple inheritances) ?
(I wish to gather the information from experienced hands).
Edit :
Edited to be concept centric,i guess.
The point is, you could also have a class Bike which implements IRide, without inheriting from Animal. You can think of an interface as being an abstract contract, specifying that objects of this class can do the things specified in the interface.
Because C# doesn't support multiple inheritance (which is a good thing IMHO) interfaces are the way you specify shared behavior or state across otherwise unrelated types.
interface IRideable
{
void Ride();
}
class Elephant : Animal, IRideable{}
class Unicycle: Machine, IRideable{}
In this manner, say you had a program that modeled a circus (where machines and animals had distinct behavior, but some machines and some animals could be ridden) you can create abstract functionality specific to what is means to ride something.
public static void RideThemAll(IEnumerable<IRideable> thingsToRide)
{
foreach(IRideable rideable in thingsToRide)
ridable.Ride();
}
As Lucero points out, you could implement other classes that implement IRide without inherting from Animal and be able to include all of those in your IRide[] array.
The problem is that your IRide interface is still too broad for your example. Obviously, it needs to include the Ride() method, but what does the Eat() method have to do with being able to ride a "thing"?
Interfaces should thought of as a loose contract that guarantees the existance of a member, but not an implementation. They should also not be general enough to span "concepts" (eating and riding are two different concepts).
You are asking the difference between abstract classes and interfaces. There is a really good article on that here.
Another great advantage is lower coupling between software components. Suppose you want to be able to feed any rideable animal. In this case you could write the following method:
public void Feed(IRide rideable)
{
//DO SOMETHING IMPORTANT HERE
//THEN DO SOMETHING SPECIFIC TO AN IRide object
rideable.Eat();
}
The major advantage here is that you can develop and test the Feed method without having any idea of the implementation of IRide passed in to this method. It could be an elephant, horse, or donkey. It doesn't matter. This also opens up your design for using Inversion of Control frameworks like Structure Map or mocking tools like Rhino Mock.
Interfaces can be used for "tagging" concepts or marking classes with specifically functionality such as serializable. This metadata (Introspection or Reflection) can be used with powerful inversion-of-control frameworks such as dependency injection.
This idea is used throughout the .NET framework (such as ISerializable) and third-party DI frameworks.
You already seem to grasp the general meaning of Interfaces.
Interfaces are just a contract saying "I support this!" without saying how the underlying system works.
Contrast this to a base or abstract class, which says "I share these common properties & methods, but have some new ones of my own!"
Of course, a class can implement as many interfaces as it wants, but can only inherit from one base class.

Categories

Resources