Home IT News Easy methods to use the specification design sample in C#

Easy methods to use the specification design sample in C#

0
Easy methods to use the specification design sample in C#

[ad_1]

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 principles 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е strategy to dеfinе and combinе businеss rulеs or circumstances in a rеusablе and maintainablе manner, 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 benefit from it in C#, offering a lot of code examples as an instance the ideas.

Create a console utility mission in Visible Studio

First off, let’s create a .NET Core console utility mission 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 mission.

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

We’ll use this .NET 7 console utility mission 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 method 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.

By utilizing a specification design sample, you isolate the validation logic from the enterprise entities to which it’s utilized. That is completed by introducing a specification object that encapsulates a situation and exposes a technique for figuring out whether or not a selected 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 method. This in flip improves the group, testability, and reusability of your code. Enterprise guidelines and circumstances may be extra simply represented while you use the specification design sample.

By utilizing the specification sample, you possibly can:

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

Implementing the specification design sample in C#

To get began implementing the specification sample, you possibly can first design the ISpecification interface. This can have one methodology 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 will 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 methodology 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 straightforward to mix specs. You possibly can mix specs utilizing the logical operators (AND, OR, NOT) to characterize advanced circumstances 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 lessons to implement circumstances

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

public class AndSpecification<T> : SpecificationBase<T>
{
    non-public readonly SpecificationBase<T> _leftSpecification;
    non-public 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>
{
    non-public readonly SpecificationBase<T> _leftSpecification;
    non-public readonly SpecificationBase<T> _rightSpecification;
    public OrSpecification(SpecificationBase<T> leftSpecification, SpecificationBase<T> rightSpecification)
    {
        _leftSpecification = leftSpecification;
        _rightSpecification = rightSpecification;
    }
    public override bool IsSatisfied(T merchandise)
    
}
public class NotSpecification<T> : SpecificationBase<T>
{
    non-public readonly SpecificationBase<T> _specification;
    public NotSpecification(SpecificationBase<T> specification)
    {
        _specification = specification;
    }
    public override bool IsSatisfied(T merchandise)
    {
        return !specification.IsSatisfied(merchandise);
    }
}

Create lessons to implement specs

Now, create two further lessons that characterize concrete specs—one for full-time standing and the opposite for the fundamental 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 circumstances

Lastly, you possibly can write the next piece of code to examine if the circumstances 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 circumstances are happy...");
else
    Console.WriteLine("The circumstances usually are not happy...");
Console.ReadLine();

As a result of the worth of the Fundamental property of the worker object is 1000, while you execute the above piece of code, you’ll see the textual content “The circumstances 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 manner. You should utilize the specification design sample in scenerios that require the validation of circumstances, querying and filtering information, imposing enterprise guidelines, and evaluating advanced circumstances. It’s a really helpful sample to have in your toolkit.

Copyright © 2023 IDG Communications, Inc.

[ad_2]

LEAVE A REPLY

Please enter your comment!
Please enter your name here