Search code examples
c#interfaceabstractionsolid-principlesdependency-inversion

Is this a valid use of DIP (SOLID)?


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
}

Solution

  • 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