Interface enhancement

I used a lot of abstract classes for both polymorphism and obviously inheriting a common function in subclasses.

I try to use interfaces more. Yes, it is also used for polymorphism ... for example, using the IMyInterface parameter in a method that can accept any subclass that implements IMyInterface.

Well, now I don’t understand why we should or should always define our variables as IMyInterface, and not the type that implemented this interface.

Example: take a look at this article:

http://weblogs.asp.net/sfeldman/archive/2008/02/14/understanding-ioc-container.aspx

Well, in particular this:

  17:      private static void AppCode()
  18:      {
  19:        ConsoleLogger logger = new ConsoleLogger();
  20:        Gadget gadget = new Gadget(logger);
  21:        gadget.TurnOn();
  22:        gadget.TurnOff();
  23:      }
  24:    }
  25:  }

AppCode method (lines 19-22) is what we are interested in. A few question can be raised at this point:

   1. Why logger is of type ConsoleLogger and not ILogger? Isn't this wrong?
   2. Why gadget is of type Gadget and not IGadget? Same smell?
   3. What if we need to move logger implementer to a different layer than the ConsoleApp?

, , Gadget ConsoleLogger. var ILogger IGadget? , ... , , , .

- , , ? Gadget ConsoleLogger, , ? Gadget ConsoleLogger ILogger IGadget... . .

, , , , , . ?

, , , , , , , ?

+3
1

, , Gadget ConsoleLogger. var ILogger IGadget? , ... , , , .

inversion of control , , . - Program . - implementation!

, Program - , . , ConsoleLogger SyslogLogger CompositeLogger, .

( ) - - . - - , , , xml. ( ) - .

http://en.wikipedia.org/wiki/Inversion_of_control - , ))

UPD

- Program ConsoleLogger. , "" . , (, ConsoleLogger ) - ​​ . . == Program ConsoleLogger , , Program , .

dependency container - , / ( , ).

+6

Source: https://habr.com/ru/post/1771626/


All Articles