Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Must Inject the Specifications on Business Layer?

I'm trying to learn somethings about Dependency Injection and Specification Pattern.

If I have this scenario: I have three methods and they have different validation rules. This rules are validated by Specifications. So... My class must receive on the constructor these Specifications like this?

public PostService(IRepositorio rep, ISpecificationSave ss, SpecificationGet g, ISpecificationDelete sd) { 
  // do things...
}

But if is this correct, when I add a new method, I need to change de constructor to receive more one Specification?

Or, even using Dependency Inject, is better, in this case, create an instance of Specification on method how's use the Specification like that:

public void DoSomeThing(MyObject object) {
     Specification<MyObject> specification = new Specification<MyObject>();
     // do things...
}

I know the question is simple for some one of you, but I'm trying to learn those kinds of patterns yet.

like image 234
Rubens Avatar asked Nov 08 '22 12:11

Rubens


1 Answers

You can use these Specifications in each validator by them adding one by one in your class, using Specitication Pattern, as follow:

public Class Class1 : IClass1 {
    private List<ISpecification> contents;
    private List<ISpecification> specializations;

    public List GetContents() {
        return contents;
    }

    public Set GetFeatures() {
         return specifications;      
    }

    public Class1() {
        features = new List<ISpecification>(){//put specializations who belongs this class here};
        specialications = new List<ISpecification>();
    }   

    public boolean Validator1() {
        foreach(ISpecification as spec in this.specializations) {
            if (!spec.GetSpecification().IsSatisfiedBy(this))
                return false;
        }
        return true;
    }
}

public class Specification1 : ISpecification {
  private object requiredFeature;

  public Specification1(object feature) {
     requiredFeature = feature;
  }

  public boolean IsSatisfiedBy(IClass class) {
     return class.GetFeatures().contains(requiredFeature);  
  }
}

Then, you can add specifications in your application by:

IClass1 class = new Class1();
class.GetFeatures().add(new Specialization1(// some feature));
class.GetFeatures().add(new Specialization2(// some feature));
class.GetFeatures().add(new Specialization3(// some feature));
like image 108
guijob Avatar answered Nov 15 '22 11:11

guijob