Coder Social home page Coder Social logo

lsolano / triplex Goto Github PK

View Code? Open in Web Editor NEW
2.0 2.0 0.0 481 KB

Validation library inspired by the concepts of Secure by Design, by Dan Bergh Johnsson, Daniel Deogun, and Daniel Sawano (MEAP 2019 Manning Publications).

License: MIT License

C# 99.48% Shell 0.52%
invariants triplex preconditions postconditions ddd open-source opensource

triplex's Introduction

Triplex

Validation library inspired by the concepts of Secure by Design, by Dan Bergh Johnsson, Daniel Deogun, and Daniel Sawano (MEAP 2019 Manning Publications). (Preconditions, Postconditions, Invariants & Proto-Primitives at https://docs.microsoft.com/en-us/dotnet/framework/debug-trace-profile/code-contracts)

Project's Code Health

Overall

Sonarcloud Status

Ratings

SQALE Rating SQALE Index Reliability Rating Security Rating

Types of validations

Arguments

Remember that arguments are actual values to methods declared parameters. The utility class used to validate arguments is Triplex.Validations.Arguments. If an argument is invalid this utility will throw an System.ArgumentException or one of its derivatives.

Object's state

Sometimes we need to check internal state before or after certain operation to ensure preconditions and invariants respectively. To check for those we use Triplex.Validation.State utility. This one throws System.InvalidOperationException or one of its derivatives.


Examples

Arguments

using Triplex.Validations;

public sealed class Email
{
	private readonly string _value;

	public Email(string value) {
		Arguments.NotNull(value);
		Arguments.LengthBetween(value, 12, 60);
		Arguments.MatchesPattern(value.ToLowerInvariant(), "^[a-zA-Z.][email protected]$");
		
		_value = value.ToLowerInvariant();
	}
}

All methods has three forms:

  1. Data only, no argument name, nor custom message. Like Arguments.NotNull(someArg);
  2. Data, argument name, but no custom message. Like Arguments.NotNull(someArg, nameof(someArg));
  3. Data, argument name, and custom message. Like Arguments.NotNull(someArg, nameof(someArg), "Your custom exception message goes here");

Object's state

using Triplex.Validations;

public sealed class Point
{
	//private Point stuff here...

	//Useful constructor(s) here
	//public Point(...) { }

	public void MoveBy(int x, int y, int z) {
		//1. Any relevant arguments validations here using Arguments util
		Arguments.All(x, y, z).NotEqualTo(default(int));

		//2. Do your stuff
		ComplexMoveLogic(x, y, z);
		
		//3. Afther moving, could not be outside map's boundaries
		State.StillHolds(_theMap.IsStrictlyWithin(this)); // throws if false
	}
}

All methods has two forms:

  1. Data only, no custom message. Like State.StillHolds(somePostActionValidation);
  2. Data, argument name, but no custom message. Like State.StillHolds(somePostActionValidation, "Your custom exception message goes here");

There is no argument name, because State is used to validate objects internal state, as a hole, or invariants.

We like to get help from everybody, if you want to contribute to this tool, found some issue or just want a feature request please read, first, the Contributing guide.

triplex's People

Contributors

juandozuna avatar lsolano avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar

triplex's Issues

Publish action fails on rm of old packages

Describe the bug
The publish action fails trying to remove old versions when the folder is empty.

Run rm src/Validations/bin/Release/Triplex.Validations*.nupkg
rm: cannot remove 'src/Validations/bin/Release/Triplex.Validations*.nupkg': No such file or directory
Error: Process completed with exit code 1.

To Reproduce
Steps to reproduce the behavior:

  1. Create a release, with a new tag, to trigger the action.
  2. Wait for the puglish workflow to run "Publish in Nuget.org V3 Package Registry" (current name).
  3. Wait for the error on the rm step (Clean old Packages)

Expected behavior
The rm command should be forced to avoid false negatives.

Suppress null possibility

Is your feature request related to a problem? Please describe.

        private string GetCurrentUserEmail()
        {
            string email = Arguments.NotNull(HttpContext.User.Identity, nameof(HttpContext.User.Identity));

            return email;
        } 

Describe the solution you'd like
It threw me a warning of possible null

Describe alternatives you've considered

   private string GetCurrentUserEmail()
        {
            string email = Arguments.NotNull(HttpContext?.User?.Identity, nameof(HttpContext.User.Identity));

            return email;
        }
 public static TParamType NotNullJavier<TParamType>(in TParamType? value, in string paramName) where TParamType : class
        {
            return value ?? throw new ArgumentNullException(paramName: paramName);
        }

Additional context

Add source code analysis with Sonarqube

Is your feature request related to a problem? Please describe.
Allow users to see sonar quality ratings.

Describe the solution you'd like

  1. Any time the project gets build on main branch (master), it should trigger a build on sonar public instance sonarcloud.io.
  2. Add sonarqube quality badges to Reame.md

Use NotNull and CallerArgumentExpression attributes from .NET 6 to reduce messages parameters

Is your feature request related to a problem? Please describe.

Argument name:
The following pattern is a litter verbose:

public sealed class Foo
{
  //For EVERY call we need to add namof ...
  public Foo(Bar bar) => MyBar = Arguments.NotNull(bar, nameof(bar));
  
  public Bar MyBar { get; }
}

Reduce Compiler Warnings:
Do use [return: NotNull] and [NotNull] for methods return and parameters respectively.

public static class Arguments
{
  [DebuggerStepThrough]
  [return: NotNull] //Add this attribute for every method to tell the compiler that returned values wont be null. 
  public static TParamType OrException<TParamType>(
    //Add NotNull to all parameters to declare that will be not-null if the method returns
    [NotNull] TParamType? value, ...
}

Describe the solution you'd like
Do add the described Attributes to all public methods corresponding parameters.

Describe alternatives you've considered
None.

Additional context
Take advantage of .NET 6 new features.

Increase test coverage to 100%

Is your feature request related to a problem? Please describe.
In order to avoid hidden bugs with future changes we need to ensure a 100% test coverage.

Describe the solution you'd like
Add missing test until all cases get covered.

Describe alternatives you've considered
None.

Additional context
None.

Ability to validate an arbitrary precondition in the form of a Boolean expression

Is your feature request related to a problem? Please describe.
When we have to check complex preconditions over one or more parameters we need to create a ad-hoc if statement:

public void DoStuffWith(SomeClass theParameter) {
  Arguments.NotNull(theParameter, nameof(theParameter);

  //Check if some date, within the argument, is not behind one full day from now.
  var differenceWithNow = (theParameter.TheDateTimeProperty - DateTimeOffset.UtcNow);
  if ( differenceWithNow < TimeSpan.FromDays(-1)) {
    throw new ArgumentException(paramName: nameof(theParameter), message: "Date is older than one(1) day.");
  }
  
// rest of method goes here ...
}

Describe the solution you'd like
We could have something like

public void DoStuffWith(SomeClass theParameter) {
  Arguments.NotNull(theParameter, nameof(theParameter);
    
  //Check if some date, within the argument, is not behind one full day from now.
  var differenceWithNow = (theParameter.TheDateTimeProperty - DateTimeOffset.UtcNow);
  Arguments.CompliesWith(differenceWithNow >= TimeSpan.FromDays(-1), nameof(theParameter), "Date can not be more than one day past.");
  
  // rest of method goes here ...
}

The signature could be something like:
public static void CompliesWith(in bool precondition, in string paramName, in string preconditionDescription)
Because this is a custom check the description (last parameter) is always required.

Describe alternatives you've considered
None.

Additional context
None.

Allow publish for 1.x, 2.x, 3.x tags

Is your feature request related to a problem? Please describe.
Unable to publish from Github.

Describe the solution you'd like
Allow publish action to run automatically for all versions (1, 2, and 3).

Remove small quality gate status badge and leave only the big one

Is your feature request related to a problem? Please describe.
This is not a problem, just a redundant information and need to be addressed to avoid misinformation.

Describe the solution you'd like
Use only the Big Quality Gate Status Badge. Remove the small (second one).
image

Describe alternatives you've considered
None so far.

Additional context
None.

Nuget push failing

Describe the bug
Nuget push fails

To Reproduce
Steps to reproduce the behavior:

  1. Publish new release with a new tag
  2. Wait for dotnet nuget push

Expected behavior
Publish with glob patern, trying "**/*.nupkg" as indicated here.

Note

If this command doesn't work, it might be due to a bug that existed in older versions of the SDK (.NET Core 2.1
SDK and earlier versions). To fix this, upgrade your SDK version or run the following command instead: dotnet nuget push "**/*.nupkg"

Add implicit null checks for

Method from Arguments to migrate and deprecate:

  • NotNullEmptyOrWhiteSpaceOnly -> NotEmptyOrWhiteSpaceOnly
  • NotNullOrEmpty -> NotEmpty

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.