-
Notifications
You must be signed in to change notification settings - Fork 6
Aspekt Contracts Usage
ASPeKT Contracts is a light-weight contracts library, built on the ASPeKT Foundation. Allowing for method contracts and invariants to be described by attributes. This removes the noisy null checks and entry/exit validation that can cloud the codes real intent and make readability harder.
ASPeKT Contract usage is quite straightforward, simply dress methods with the RequiresArgument or Invariant attribute and let the ASPeKT Foundation take care of the rest.
[FieldInvariant("myInt", Contract.Comparison.NotEqualTo, 5)]
[PropertyInvariant(nameof(MyProperty), Contract.Constraint.NotNull)]
class Foo
{
[RequiresArgument("value", typeof(int), Contract.Comparison.GreaterThan, 5)]
void MethodNeeds5OrHigher(int value)
{
}
[RequiresArgument(0,typeof(string),Contract.Comparison.EqualTo, "Seasame")]
int Open(string argument)
{
return 3;
}
[NotNull("argument")]
void Close(string argument)
{
}
int myInt = 0;
public string MyProperty { get; set; } = "NotNull";
}
RequiresArgument attribute lets you specify comparison of an argument. It uses the IComparison on the argument vs the expected value. Given that attributes only let you specify simple data types in attribute constructors it isn't possible to do comparison on user classes. You can also constrain the argument reference to either be null or not-null. This avoids the class if null check at the beginning of each method.
Invariant attribute lets you specify both comparison or constraints against fields or properties on a class. The check is done when entering and exiting the method. This is to ensure class invariants do not get violated.
Invariants are applied at a class level, allowing you to document rules about your class that can never be violated. A violation will result in a thrown exception.
- Working on a Returns attribute, but this involves work in Aspekt Foundation