Invariants are methods that verify the consistency of the state of the current object and throw an exception if inconsistencies are found. We recommend throwing an exception of type InvariantViolationException, but the final decision is entirely up to you.
Adding invariants
To add an invariant to a class:
- Create a
void
, non-static
, and parameterless method in your class. This method should typically beprivate
. - Add the [Invariant] custom attribute to this method.
- Add the validation logic to this method and throw an InvariantViolationException in case of a violation.
Warning
An invariant method should not have any side effects other than throwing an exception in case of an invariant violation.
Example: adding invariants
In the following example, an Invoice
entity has two properties, DiscountPercent
and DiscountAmount
, that allow providing discounts. These two properties are additive, but their sum cannot result in a negative price. The CheckDiscounts
method enforces this condition.
1using Metalama.Patterns.Contracts;
2
3namespace Doc.Invariants;
4
5public class Invoice
6{
7 public decimal Amount { get; set; }
8
9 [Range( 0, 100 )]
10 public int DiscountPercent { get; set; }
11
12 [Range( 0, 100 )]
13 public decimal DiscountAmount { get; set; }
14
15 public virtual decimal DiscountedAmount
16 => (this.Amount * (100 - this.Amount) / 100m) - this.DiscountAmount;
17
18 [Invariant]
19 private void CheckDiscounts()
20 {
21 if ( this.DiscountedAmount < 0 )
22 {
23 throw new PostconditionViolationException(
24 "The discounted amount cannot be negative." );
25 }
26 }
27}
1using System;
2using Metalama.Patterns.Contracts;
3
4namespace Doc.Invariants;
5
6public class Invoice
7{
8 private decimal _amount;
9
10 public decimal Amount
11 {
12 get
13 {
14 return _amount;
15 }
16
17 set
18 {
19 try
20 {
21 _amount = value;
22 return;
23 }
24 finally
25 {
26 this.VerifyInvariants();
27 }
28 }
29 }
30
31 private int _discountPercent;
32
33 [Range(0, 100)]
34 public int DiscountPercent
35 {
36 get
37 {
38 return _discountPercent;
39 }
40
41 set
42 {
43 try
44 {
45 if (value is < 0 or > 100)
46 {
47 throw new ArgumentOutOfRangeException("value", value, "The 'DiscountPercent' property must be in the range [0, 100].");
48 }
49
50 _discountPercent = value;
51 return;
52 }
53 finally
54 {
55 this.VerifyInvariants();
56 }
57 }
58 }
59
60 private decimal _discountAmount;
61
62 [Range(0, 100)]
63 public decimal DiscountAmount
64 {
65 get
66 {
67 return _discountAmount;
68 }
69
70 set
71 {
72 try
73 {
74 if (value is < 0M or > 100M)
75 {
76 throw new ArgumentOutOfRangeException("value", value, "The 'DiscountAmount' property must be in the range [0, 100].");
77 }
78
79 _discountAmount = value;
80 return;
81 }
82 finally
83 {
84 this.VerifyInvariants();
85 }
86 }
87 }
88
89 public virtual decimal DiscountedAmount
90 => (this.Amount * (100 - this.Amount) / 100m) - this.DiscountAmount;
91
92 [Invariant]
93 private void CheckDiscounts()
94 {
95 if (this.DiscountedAmount < 0)
96 {
97 throw new PostconditionViolationException(
98 "The discounted amount cannot be negative.");
99 }
100 }
101
102 protected virtual void VerifyInvariants()
103 {
104 CheckDiscounts();
105 }
106}
Opting out from invariant checking
When a type has any invariant, the implementation of all public or internal methods in this type will be wrapped into a try...finally
block, and invariants will be verified from the finally
block.
To prevent a method from being enhanced with this invariant checking logic, you can use the [DoNotCheckInvariants] custom attribute.
Note that this will not waive the enforcement of invariants in methods called by the target of the [DoNotCheckInvariants] attribute. Therefore, this attribute is mainly useful to optimize performance, not to relax invariants.
Suspending enforcement of invariants
If you have a code snippet that temporarily breaks invariants, you can suspend invariant enforcement.
First, enable the IsInvariantSuspensionSupported option for this type. This option is disabled by default because it generates additional code. You can set this option from a ProjectFabric or NamespaceFabric as described in Configuring contracts.
Once this feature is enabled, there are two ways to suspend invariant enforcement:
- To disable enforcement while the entire method is executing, add the [SuspendInvariants] custom attribute to this method.
- To disable enforcement while a code snippet is executing, wrap this snippet in a call to
using ( this.SuspendInvariants() )
. TheSuspendInvariants
method is generated by the IsInvariantSuspensionSupported option.
Example: suspending invariants
The following example builds upon the previous one. We added a fabric to enable the IsInvariantSuspensionSupported option. The Invoice
method now has two new methods, UpdateDiscounts1
and UpdateDiscounts2
, which update DiscountPercent
and DiscountAmount
while suspending invariants.