Last active
July 4, 2023 16:42
-
-
Save kemsky/d7ce8a2bea0f99eeecafcef1a098a777 to your computer and use it in GitHub Desktop.
[Medium] Specification interface
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// implenation details omitted intentionally | |
public sealed class Specification<TSource> | |
{ | |
// for expression based APIs | |
public Expression<Func<TSource, bool>> IsSatisfiedByExpression { get; } | |
// for regular code | |
public Func<TSource, bool> IsSatisfiedBy { get; } | |
// create specification from expression | |
public Specification(Expression<Func<TSource, bool>> expressionFunc) | |
// create specification from expression and delegate | |
public Specification(Expression<Func<TSource, bool>>? expressionFunc, Func<TSource, bool> delegateFunc) | |
// combination support: combinedSpec = spec1 && spec2 | |
public static Specification<TSource> operator &(Specification<TSource> spec1, Specification<TSource> spec2) | |
// combination support: combinedSpec = spec1 || spec2 | |
public static Specification<TSource> operator |(Specification<TSource> spec1, Specification<TSource> spec2) | |
// false operator required to prevent short-circuit and force evaluate both specs: spec1 && spec2 | |
public static bool operator false(Specification<TSource> _) => false; | |
// true operator used by if, while statements etc. required as pair to the false operator | |
public static bool operator true(Specification<TSource> _) => false; | |
// easy negation: negatedSpec = !somespec | |
public static Specification<TSource> operator !(Specification<TSource> specification) | |
// simplify usage by implicitly converting specification to Func<TSource, bool> | |
public static implicit operator Func<TSource, bool>(Specification<TSource> f) | |
// simplify usage by implicitly converting specification to Expression<Func<TSource, bool>> | |
public static implicit operator Expression<Func<TSource, bool>>(Specification<TSource> f) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment