Skip to content

Evaluate Specification for one Entity #111

@JelmarVA

Description

@JelmarVA

It would be nice to use a specification to make sure an object is still valid.
I've given an example of why you'd want to share this logic in one place.

@fiseni proposed the following:

I was thinking of this, and we might introduce a new type of specification, or perhaps just a specific builder for this purpose. Conceptually, all we need is the entity as a parameter, and bool as a result, right? So, we might hold Func<T, bool> delegates.
We can have something as follows:

public class ValidVerificationCodeSpec : Specification<VerificationCode>
{
    public ValidVerificationCodeSpec()
    {
        Validators.Add(entity =>
        {
            if (entity.DateUsed == null && entity.DateCreated.AddMinutes(30) > DateTime.Now) return true;

            return false;
        }
    }
}

And the specification might expose IsValid method as follows

	
public bool IsValid(T entity)
{
    bool result = true;
    foreach (var validator in specification.validators)
    {
        result = result && validator(entity);
    }

    return result;
}

This is still not refined, but it might go along with this idea.

Let's say we add a Validator builder. This should be translatable to a query on the database right?
Or do you guys see it so they live together next to each other as following?

public class ValidVerificationCodeSpec : Specification<VerificationCode>
{
    public ValidVerificationCodeSpec()
    {
        Query
            .Where(vc => vc.DateUsed == null)
            .Where(vc => vc.DateCreated.AddMinutes(30) > DateTime.Now);

        Validators.Add(entity =>
        {
            if (entity.DateUsed == null && entity.DateCreated.AddMinutes(30) > DateTime.Now) return true;

            return false;
        }
    }
}

That will result in some duplication of the logic.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions