Motiv 7.4.3

dotnet add package Motiv --version 7.4.3                
NuGet\Install-Package Motiv -Version 7.4.3                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Motiv" Version="7.4.3" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Motiv --version 7.4.3                
#r "nuget: Motiv, 7.4.3"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Motiv as a Cake Addin
#addin nuget:?package=Motiv&version=7.4.3

// Install Motiv as a Cake Tool
#tool nuget:?package=Motiv&version=7.4.3                

Motiv

Build Status NuGet codecov

Know Why, not just What

Motiv is a developer-first .NET library that transforms the way you work with boolean logic. It lets you form expressions from discrete propositions so that you can explain why decisions were made.

First create atomic propositions:

// Define atomic propositions
var isValid = Spec.Build((int n) => n is >= 0 and <= 11).Create("valid");
var isEmpty = Spec.Build((int n) => n == 0).Create("empty");
var isFull  = Spec.Build((int n) => n == 11).Create("full");

Then compose using operators (e.g., !, &, |, ^):

// Compose a new ad-hoc proposition
var composed = isValid & !(isEmpty | isFull);

// Give it a new name
var isPartiallyFull = Spec.Build(composed).Create("partial");

To get detailed feedback:

// Evaluate the proposition against a model/value
var result = isPartiallyFull.IsSatisfiedBy(5);

result.Satisfied;         // true
result.Reason;            // "partial"
result.UnderlyingReasons; // ["valid & !(¬empty | ¬full)"]
result.SubAssertions;     // ["valid", "¬empty", "¬full"]
result.Justifications     // partial
                          //     AND
                          //         valid
                          //         NOR
                          //             ¬empty
                          //             ¬full

Why Use Motiv?

Motiv primarily gives you visibility into your application's decision-making process. By decomposing expressions into propositions, it addresses important architectural concerns and enables more advanced use cases, such as implementing dynamic logic or determining state.

Consider using Motiv if your project requires two or more of the following:

  1. Visibility: Provide detailed, real-time feedback about decisions made.
  2. Decomposition: Break down complex logic into meaningful subclauses for improved readability.
  3. Reusability: Reuse logic across multiple locations to reduce duplication.
  4. Modeling: Explicitly model your domain logic.
  5. Testing: Simplify the testing your logic without mocking or stubbing dependencies.

Use Cases

Motiv can be applied in various scenarios, including:

  • User Feedback: Provide detailed explanations about decision outcomes.
  • Debugging: Quickly find out the causes from complex logic.
  • Multilingual Support: Offer explanations in different languages.
  • Validation: Ensure user input meets specific criteria and provide detailed feedback.
  • Dynamic Logic: Compose logic at runtime based on user input.
  • Rules Processing: Declaratively define and compose complex if-then rules.
  • Conditional State: Yield different states based on complex criteria.
  • Auditing: Log why something happened, instead of what happened.

Installation

Install Motiv via NuGet Package Manager Console:

Install-Package Motiv

Or using the .NET CLI:

dotnet add package Motiv

Usage

Basic Proposition

Create and evaluate a basic proposition:

var isEligibleForLoan =
    Spec.Build((Customer customer) =>
            customer is
            {
                CreditScore: > 600,
                Income: > 100000
            })
        .Create("eligible for loan");

var result = isEligibleForLoan.IsSatisfiedBy(eligibleCustomer);

result.Satisfied;  // true
result.Reason;     // "eligible for loan"
result.Assertions; // ["eligible for loan"]

Propositions with Custom Assertions

Use WhenTrue() and WhenFalse() for user-friendly explanations:

var isEligibleForLoan =
    Spec.Build((Customer customer) =>
            customer is
            {
                CreditScore: > 600,
                Income: > 100000
            })
        .WhenTrue("eligible for a loan")
        .WhenFalse("not eligible for a loan")
        .Create();

var result = isEligibleForLoanPolicy.IsSatisfiedBy(ineligibleCustomer);

result.Satisfied;  // false
result.Reason;     // "not eligible for a loan"

Propositions with Custom Metadata

Use WhenTrue() and WhenFalse() with types other than string:

var isEligibleForLoanPolicy =
    Spec.Build((Customer customer) =>
            customer is
            {
                CreditScore: > 600,
                Income: > 100000
            })
        .WhenTrue(MyEnum.EligibleForLoan)
        .WhenFalse(MyEnum.NotEligibleForLoan)
        .Create("eligible for a loan");

var result = isEligibleForLoanPolicy.IsSatisfiedBy(eligibleCustomer);

result.Satisfied;  // true
result.Value;      // MyEnum.EligibleForLoan
result.Reason;     // "eligible for a loan"

Composing Propositions

Combine propositions using boolean operators:

var hasGoodCreditScore =
    Spec.Build((Customer customer) => customer.CreditScore > 600)
        .WhenTrue("good credit score")
        .WhenFalse("inadequate credit score")
        .Create();

var hasSufficientIncome =
    Spec.Build((Customer customer) => customer.Income > 100000)
        .WhenTrue("sufficient income")
        .WhenFalse("insufficient income")
        .Create();

var isEligibleForLoan = hasGoodCreditScore & hasSufficientIncome;

var result = isEligibleForLoan.IsSatisfiedBy(eligibleCustomer);

result.Satisfied;  // true
result.Reason;     // "good credit score & sufficient income"
result.Assertions; // ["good credit score", "sufficient income"]

Higher Order Logic

Provide facts about collections:

var allNegative =
    Spec.Build((int n) => n < 0)
        .AsAllSatisfied()
        .WhenTrue("all are negative")
        .WhenFalseYield(eval => eval.FalseModels.Select(n => $"{n} is not negative"))
        .Create();

var result = allNegative.IsSatisfiedBy([-1, 2, 3]);

result.Satisfied;  // false
result.Reason;     // "¬all are negative"
result.Assertions; // ["2 is not negative", "3 is not negative"]

Tradeoffs

Consider these potential tradeoffs when using Motiv:

  1. Performance: Motiv isn't optimized for high-performance scenarios where nanoseconds matter.
  2. Dependency: Once integrated, Motiv becomes a core dependency in your codebase.
  3. Learning Curve: While Motiv introduces a new approach, it's designed to be intuitive and easy to use.

License

Motiv is released under the MIT License. See the LICENSE file for details.

Resources

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.