You are currently viewing Learn how to use the specification design sample in C#

Learn how to use the specification design sample in C#


Whеn wе work in enterprise purposes, our job is to writе businеss logic that implements thе businеss rulеs—i.e., the foundations that our firm has specified for utility. How can we make this job simpler? A technique is to make use of the specification design sample.

Thе spеcification dеsign pattеrn providеs a flеxiblе option to dеfinе and combinе businеss rulеs or situations in a rеusablе and maintainablе method, thereby selling sеparation of concеrns and rеducing codе duplication.

On this article, I’ll introduce the specification design sample and present how we are able to make the most of it in C#, offering numerous code examples for instance the ideas.

Create a console utility undertaking in Visible Studio

First off, let’s create a .NET Core console utility undertaking in Visible Studio. Assuming Visible Studio 2022 is put in in your system, comply with the steps outlined under to create a brand new .NET Core console utility undertaking.

  1. Launch the Visible Studio IDE.
  2. Click on on “Create new undertaking.”
  3. Within the “Create new undertaking” window, choose “Console App (.NET Core)” from the record of templates displayed.
  4. Click on Subsequent.
  5. Within the “Configure your new undertaking” window, specify the title and placement for the brand new undertaking.
  6. Click on Subsequent.
  7. Within the “Further data” window proven subsequent, select “.NET 7.0 (Normal Time period Help)” because the Framework model you want to use.
  8. Click on Create.

We’ll use this .NET 7 console utility undertaking to work with the specification design sample within the subsequent sections of this text.

What’s the specification design sample?

Thе spеcification dеsign pattеrn providеs a modular and structurеd strategy to dеfining your businеss rulеs and mixing thеm in thе utility. This lets you makе your sourcе codе simpler to take care of, tеst, and rеuse whilе еncapsulating businеss rulеs inside spеcification objеcts.

Through the use of a specification design sample, you isolate the validation logic from the enterprise entities to which it’s utilized. That is achieved by introducing a specification object that encapsulates a situation and exposes a technique for figuring out whether or not a specific object satisfies it.

Why use the specification design sample?

Within the specification sample, standards and guidelines are outlined, encapsulated, and made reusable utilizing an object-oriented strategy. This in flip improves the group, testability, and reusability of your code. Enterprise guidelines and situations may be extra simply represented if you use the specification design sample.

Through the use of the specification sample, you may:

  • Modularize code: Specs encapsulate enterprise guidelines and situations in separate courses, making them simpler to know, modify, and keep. As well as, they assist keep a clear and targeted code base by isolating the considerations in an utility.
  • Enhance reusability: Specs may be reused with related validation logic throughout utility elements. You possibly can keep away from code duplication and guarantee constant validation all through the system by encapsulating the foundations in reusable specification objects.
  • Dynamic composition: Specs may be mixed utilizing logical operators comparable to AND, OR, and NOT to create advanced situations. Combining a number of specs permits you to create dynamic queries or filters.
  • Streamline testing: Specs symbolize particular person enterprise guidelines, making them simple to check in isolation. In consequence, unit assessments are simpler to write down and the validation logic is extra sturdy.

Implementing the specification design sample in C#

To get began implementing the specification sample, you may first design the ISpecification interface. It will have one technique referred to as IsSatisfied that accepts an object as a parameter and returns a boolean worth primarily based on whether or not the thing handed as a parameter satisfies the requisite specification.

public interface ISpecification<T>
{
    bool IsSatisfied(T merchandise);
}

We are able to now create a category named IncentiveSpecification that checks whether or not an worker is eligible for incentives as proven within the code snippet given under.

public class IncentiveSpecification : ISpecification<Worker>
{
 public bool IsSatisfied<Worker worker>
 {
    return worker.Fundamental >=5000 && worker.IsFullTime;
 }
}

Within the previous code snippet, the IsSatisfied technique checks if the Fundamental property of worker is larger than or equal to 5000 and if the worker is a full-time worker. If this situation is happy, the code returns true, false in any other case.

Creating and mixing specs in C#

The specification design sample makes it simple to mix specs. You possibly can mix specs utilizing the logical operators (AND, OR, NOT) to symbolize advanced situations in your utility’s code. Create a brand new C# summary base class named Specification and enter the next code.

public summary class SpecificationBase<T> : ISpecification<T>
{
    public summary bool IsSatisfied(T merchandise);
    public Specification<T> And(Specification<T> specification)
    {
        return new AndSpecification<T>(this, specification);
    }
    public Specification<T> Or(Specification<T> specification)
    {
        return new OrSpecification<T>(this, specification);
    }
    public Specification<T> Not()
    {
        return new NotSpecification<T>(this);
    }
}

Create courses to implement situations

Now create concrete implementation courses of the AndSpecification, OrSpecification, and NotSpecification specs as proven within the code itemizing given under.

public class AndSpecification<T> : SpecificationBase<T>
{
    personal readonly SpecificationBase<T> _leftSpecification;
    personal readonly SpecificationBase<T> _rightSpecification;
    public AndSpecification(SpecificationBase<T> leftSpecification, SpecificationBase<T> rightSpecification)
    {
        _leftSpecification = leftSpecification;
        _rightSpecification = rightSpecification;
    }
    public override bool IsSatisfied(T merchandise)
    {
        return _leftSpecification.IsSatisfied(merchandise) && _rightSpecification.IsSatisfied(merchandise);
    }
}
public class OrSpecification<T> : SpecificationBase<T>
{
    personal readonly SpecificationBase<T> _leftSpecification;
    personal readonly SpecificationBase<T> _rightSpecification;
    public OrSpecification(SpecificationBase<T> leftSpecification, SpecificationBase<T> rightSpecification)
    {
        _leftSpecification = leftSpecification;
        _rightSpecification = rightSpecification;
    }
    public override bool IsSatisfied(T merchandise)
     _rightSpecification.IsSatisfied(merchandise);
    
}
public class NotSpecification<T> : SpecificationBase<T>
{
    personal readonly SpecificationBase<T> _specification;
    public NotSpecification(SpecificationBase<T> specification)
    {
        _specification = specification;
    }
    public override bool IsSatisfied(T merchandise)
    {
        return !specification.IsSatisfied(merchandise);
    }
}

Create courses to implement specs

Now, create two further courses that symbolize concrete specs—one for full-time standing and the opposite for the essential specification as proven within the code snippet given under.

public class FullTimeSpecification : Specification<Worker>
{
    public override bool IsSatisfied(Worker worker)
    {
        return worker.IsFullTime;
    }
}
public class BasicSpecification : Specification<Worker>
{
   public override bool IsSatisfied(Worker worker)
    {
        return worker.Fundamental >= 5000;
    }
}

Validate specs towards situations

Lastly, you may write the next piece of code to examine if the situations are happy.

Worker worker = new Worker();
worker.FirstName = "Joydip";
worker.LastName = "Kanjilal";
worker.Fundamental = 1000;
worker.IsFullTime = true;
var basicSpecification = new BasicSpecification();
var fullTimeSpecification = new FullTimeSpecification();
var compositeSpecification = new AndSpecification<Worker>(basicSpecification, fullTimeSpecification);
var isSatisfied = compositeSpecification.IsSatisfied(worker);
if (isSatisfied)
    Console.WriteLine("The situations are happy...");
else
    Console.WriteLine("The situations usually are not happy...");
Console.ReadLine();

As a result of the worth of the Fundamental property of the worker object is 1000, if you execute the above piece of code, you’ll see the textual content “The situations usually are not happy…” displayed within the console window. 

The specification design sample lets you write code that’s structured, modular, and reusable whereas defining the enterprise guidelines of the appliance in a versatile method. You need to use the specification design sample in scenerios that require the validation of situations, querying and filtering information, imposing enterprise guidelines, and evaluating advanced situations. It’s a really helpful sample to have in your toolkit.

Copyright © 2023 IDG Communications, Inc.

Leave a Reply