Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Tuesday, July 12, 2016

C# interfaces - What's the point?

C# interfaces - What's the point?


I am from a python background and I am trying to get to grips with C#, because a couple of guys and I decided to do a project and chose C# for it (don't worry bout the reasons).

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).

But all I see is, that you predefine some members and functions, which you then have to re-define in the class again. Thus making the interface redundant because you do it all over again, so no real need in my eyes to pre-define it. 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.

I would be very grateful, if someone could shed some light on this, because it really makes no sense to me, at all :(

Thanks a lot.

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      }  }  

Answer by Claus J?rgensen for C# interfaces - What's the point?


Consider you can't use multiple inheritance in C#, and then look at your question again.

Answer by Joey for C# interfaces - What's the point?


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).

Answer by Kirill Polishchuk for C# interfaces - What's the point?


Interface = contract, used for low coupling (see GRASP).

Answer by BrokenGlass for C# interfaces - What's the point?


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.

Answer by home for C# interfaces - What's the point?


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)

Answer by Shamim Hafiz for C# interfaces - What's the point?


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      }  }  

Answer by Oscar Gomez for C# interfaces - What's the point?


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().

Answer by bevacqua for C# interfaces - What's the point?


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.

Answer by Schroedingers Cat for C# interfaces - What's the point?


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:

  1. A class can inherit from multiple interfaces. It just defines features that the class must have. Inheriting from a range of interfaces means that a class can fulfil multiple functions in different places.

  2. 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.

Answer by Samir Adel for C# interfaces - What's the point?


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.

Answer by James Black for C# interfaces - What's the point?


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.

Answer by Lasse V. Karlsen for C# interfaces - What's the point?


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 ....  }  

Answer by tam for C# interfaces - What's the point?


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.

Answer by piedpiper for C# interfaces - What's the point?


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() { ... }  }  

Answer by supercat for C# interfaces - What's the point?


The simplest way to think about interfaces is to recognize what inheritance means. If class CC inherits class C, it means both that:

  1. 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.
  2. 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.

Answer by sventevit for C# interfaces - What's the point?


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.

Answer by KallDrexx for C# interfaces - What's the point?


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 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.

Answer by ShaunnyBwoy for C# interfaces - What's the point?


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.

Answer by Paddy for C# interfaces - What's the point?


For me, 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. You could write this to start with, as there are only going to be trolls:

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();  }  

And you could extract the creation out to a factory method etc, etc... 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.

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;        switch(creatureType)      {           case Orc:               creature = new Orc();              case Troll:                creature = new Troll();      }        creature.Walk();        if (creature is ICanTurnToStone)      {         (ICanTurnToStone)creature.TurnToStone();      }  }  

C: 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.

Answer by Djacobs for C# interfaces - What's the point?


Am I correct then to take another look at Interfaces, The graphical interface (winforms / WPF) is like the Interface. It displays only what the end user will interact with. The end user will then not have to know what went into the design of the application, but would know what they can do with it, based on available options on the form. In OOP view then the idea is to create a structured interface that informs other users of your e.g DLL libraries what is available to use and that it's like an guarantee/contract that the field, methods and properties will be available to use (inherit in your classes).

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.