4

I would like to ask if that implementation of classes Genotypes and Individual violates the Dependency Inversion Principle? If so, how to fix that?

classes-abstraction hierarchy

Here is the code:

public interface IGenotype
{
   //some code...
}

public abstract class AIndividual
{
    // ... some code
    public IGenotype Genotype { get; set;}   // DIP likes that !
}

public class Individual : AIndividual
{
    public Individual()
    {
        // some code ...
        this.Genotype = new Genotype();   // Is this ok in case of DIP? 
    }
}

public class Genotype : IGenotype
{
    // ... some code
}
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574

2 Answers2

3

Dependency inversion principle deals with software modules not necessarily classes. The idea is that instead of higher-level layers depending on how lower-level layers are coded, it is better for the higher layers to define the layer interface by providing an abstract class (a C# interface serves this nicely) for the lower layers to implement and provide the services the high-level layer needs. A common mistake is to confuse this principle with dependency injection, where the dependencies are provided to a depending class by a higher level, instead of the depending class needing to find them and create them.

It seems like you are asking about dependency injection, which is "how does my depending class get an instance of my dependency?" This example looks like these two classes which belong in the same domain model, meaning they would very likely be in the same module. Having a class depend on another class and create it directly within the same module is a reasonable approach, however the Factory pattern is more robust as the classes evolve.

codekaizen
  • 26,990
  • 7
  • 84
  • 140
2

I hope this might help (please read the comments)

public interface IGenotype
{
   //some code...
}

public class Genotype : IGenotype
{
    // ... some code
}

public class Individual 
{
    // Here, instead of depending on a implementation you can inject the one you want
    private readonly IGenotype genotype; 

    // In your constructor you pass the implementation 
    public Individual(IGenotype genotype)
    {
        this.genotype = genotype;  
    }
}

// Genotype implements IGenotype interface
var genotype = Genotype();

// So here, when creating a new instance you're injecting the dependecy.
var person = Individual(genotype);

You don't need the abstract class to DIP

brduca
  • 3,573
  • 2
  • 22
  • 30