Is this a valid use of DIP (SOLID)?

I would like to ask whether violates implementation classes Genotypesand Individualthe principle of dependency inversion? If so, how to fix it?

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
}
+4
source share
2 answers

Hope this helps (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 do not need an abstract class for DIP

+2
source

, . , , , , , (# interface ) , . , , , .

, , : " ?" , , , , , . , Factory , .

+2

All Articles