dimanche 20 mai 2018

What are the patterns used to enforce business layer calls in n-layer architecture?

I'm using the n-layer architecture like below:

  • Presentation layer;
  • Application layer;
  • Business layer;
  • Data layer;

And I want to make sure my co-workers won't be able to make calls to the Data layer directly (in some cases). There is a very important business rule in the Business layer that MUST be called every time before trying to persist the entity to the database.

Here is some code demonstrating the problem:

class Program
{
    static void Main(string[] args)
    {
        //enforce business rules here (business layer usage)...
    }
}

class BusinessLayer
{
    public void ApplyBusinessRules()
    {
        //important business validation goes here...
    }
}

class DataLayer
{
    public void SaveModel()
    {
        //data acess layer goes here...
    }
}

What are the design patterns used to achieve this behavior? I've tried to set the SaveModel() method to private but people (including myself) will simply turn the method to public thinking it was some kind of typo.

I was thinking of something like this:

interface IBusinessLayerPolicy
{
    bool CheckIfModelCanBeSaved(Model model);
}

class DataLayer
{
    private IBusinessLayerPolicy _businessPolicy;

    public void SaveModel(Model model)
    {
        if(_businessPolicy.CheckIfModelCanBeSaved(model))
        {
            //save the model to database;
        }
    }
}

If that is a good approach, which class should implement IBusinessLayerPolicy interface? If not, what are the design patterns used in this case?

Aucun commentaire:

Enregistrer un commentaire