2

I'm new to patterns and am trying to understand the concept of using interfaces to prevent tight coupling. I have created a class:

public interface Imul
{
    int multi(int a, int b);
}

I implemented this interface in a separate mul class:

public class mul: Imul
{
   public int multi(int a, int b) => return a * b;
}

Now here is my problem: in the main program how should I write it to understand the concept of in-dependency?

static void Main(string[] args)
{
     // Implementation
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
mrslt
  • 337
  • 2
  • 10
  • 1
    You should ask some specific problem or difficulty. In your case, you are asking for a whole explanation almost from scratch, and Stack Overflow is not a place for that. If I were you, I'd look for a good article on the web, or a Youtube video. – Andrew Jun 03 '18 at 00:43
  • @Andrew difficulty is how should i implement it in my Main class – mrslt Jun 03 '18 at 00:55
  • Short answer: using an Inversion of Control container. Long answer: look for an article, or check that "This question already has an answer here" text above. – Andrew Jun 03 '18 at 13:16
  • @Andrew i have read many,i understood the concept,but i do not know how to implement it,how should i use IMUL in the main program,to pass parameters to my class,without instantiating the class – mrslt Jun 03 '18 at 13:23
  • Then you didn't understand it yet... The idea behind DI is to avoid tightly coupling classes. So for example, if you have a `ProcessData` class, instead of it doing `new mul().multi(x, y)`, its constructor will be like `ProcessData(Imul imul)`, it will store that parameter locally (let's say in `_imul`) and then it will call `_imul.multi(x, y)`. So `ProcessData` never creates `mul`, it simply receives it in the constructor. When instead of multiplying you need to sum values, you will just create `ProcessData` giving it as a parameter a different class that implements `Imul`. – Andrew Jun 03 '18 at 18:52
  • By the way, that interface name is probably not a good one, a better name could be `IOperation` and the method could be `Do`, so `ProcessData` would call `_ioperation.Do(x, y)`, which clearly shows it could be any type of binary operation. With an interface called `Imul`, you are saying that the class will do... only a multiplication, leaving no room for different implementations. – Andrew Jun 03 '18 at 18:52

0 Answers0