In the previous article, we created an aspect that automatically implements
the IChangeTracking interface. If the base class has a manual implementation of
the IChangeTracking, the aspect will still work correctly and call the OnChange
method of
the base class. However, what if the base class does not contain an OnChange
method or if it is not protected? Let's
improve the aspect and report an error in these situations.
The result of this aspect will be two new errors:
1namespace Metalama.Samples.Clone.Tests.MissingOnChangeMethod;
2
3[TrackChanges]
Error MY001: The 'ISwitchableChangeTracking' interface is implemented manually on type 'DerivedClass', but the type does not have an 'OnChange()' method.
4public class DerivedClass : BaseClass { }
5
6public class BaseClass : ISwitchableChangeTracking
7{
8 public bool IsChanged { get; protected set; }
9
10 public bool IsTrackingChanges { get; set; }
11
12 public void AcceptChanges()
13 {
14 if ( this.IsTrackingChanges )
15 {
16 this.IsChanged = false;
17 }
18 }
19
20 // Note that there is NO OnChange method.
21}
1namespace Metalama.Samples.Clone.Tests.OnChangeMethodNotProtected;
2
3[TrackChanges]
Error MY001: The 'ISwitchableChangeTracking' interface is implemented manually on type 'DerivedClass', but the type does not have an 'OnChange()' method.
4public class DerivedClass : BaseClass { }
5
6public class BaseClass : ISwitchableChangeTracking
7{
8 public bool IsChanged { get; protected set; }
9
10 public bool IsTrackingChanges { get; set; }
11
12 public void AcceptChanges()
13 {
14 if ( this.IsTrackingChanges )
15 {
16 this.IsChanged = false;
17 }
18 }
19
20 // Note that the OnChange method is private and not protected.
21 private void OnChange() => this.IsChanged = true;
22}
Aspect implementation
1using Metalama.Framework.Advising;
2using Metalama.Framework.Aspects;
3using Metalama.Framework.Code;
4using Metalama.Framework.Diagnostics;
5
6public class TrackChangesAttribute : TypeAspect
7{
8 private static readonly DiagnosticDefinition<INamedType> _mustHaveOnChangeMethod = new(
9 "MY001",
10 Severity.Error,
11 $"The '{nameof(ISwitchableChangeTracking)}' interface is implemented manually on type '{{0}}', but the type does not have an '{nameof(OnChange)}()' method." );
12
13 private static readonly DiagnosticDefinition _onChangeMethodMustBeProtected = new(
14 "MY002",
15 Severity.Error,
16 $"The '{nameof(OnChange)}()' method must be have the 'protected' accessibility." );
17
18 public override void BuildAspect( IAspectBuilder<INamedType> builder )
19 {
20 //
21 // Implement the ISwitchableChangeTracking interface.
22 var implementInterfaceResult = builder.Advice.ImplementInterface(
23 builder.Target,
24 typeof(ISwitchableChangeTracking),
25 OverrideStrategy.Ignore );
26
27 // If the type already implements IChangeTracking, it must have a protected method called OnChanged, without parameters, otherwise
28 // this is a contract violation, so we report an error.
29 if ( implementInterfaceResult.Outcome == AdviceOutcome.Ignore )
30 {
31 var onChangeMethod = builder.Target.AllMethods.OfName( nameof(this.OnChange) )
32 .SingleOrDefault( m => m.Parameters.Count == 0 );
33
34 if ( onChangeMethod == null )
35 {
36 builder.Diagnostics.Report( _mustHaveOnChangeMethod.WithArguments( builder.Target ) );
37 }
38 else if ( onChangeMethod.Accessibility != Accessibility.Protected )
39 {
40 builder.Diagnostics.Report( _onChangeMethodMustBeProtected );
41 }
42 }
43
44 //
45
46 // Override all writable fields and automatic properties.
47 var fieldsOrProperties = builder.Target.FieldsAndProperties
48 .Where(
49 f =>
50 !f.IsImplicitlyDeclared && f.Writeability == Writeability.All &&
51 f.IsAutoPropertyOrField == true );
52
53 foreach ( var fieldOrProperty in fieldsOrProperties )
54 {
55 builder.Advice.OverrideAccessors( fieldOrProperty, null, nameof(this.OverrideSetter) );
56 }
57 }
58
59 [InterfaceMember]
60 public bool IsChanged { get; private set; }
61
62 [InterfaceMember]
63 public bool IsTrackingChanges { get; set; }
64
65 [InterfaceMember]
66 public void AcceptChanges() => this.IsChanged = false;
67
68 [Introduce( WhenExists = OverrideStrategy.Ignore )]
69 protected void OnChange()
70 {
71 if ( this.IsTrackingChanges )
72 {
73 this.IsChanged = true;
74 }
75 }
76
77 [Template]
78 private void OverrideSetter( dynamic? value )
79 {
80 if ( value != meta.Target.Property.Value )
81 {
82 meta.Proceed();
83
84 this.OnChange();
85 }
86 }
87}
The first thing we add to the TrackChangesAttribute
is two static fields to define the errors:
8private static readonly DiagnosticDefinition<INamedType> _mustHaveOnChangeMethod = new(
9 "MY001",
10 Severity.Error,
11 $"The '{nameof(ISwitchableChangeTracking)}' interface is implemented manually on type '{{0}}', but the type does not have an '{nameof(OnChange)}()' method." );
12
13private static readonly DiagnosticDefinition _onChangeMethodMustBeProtected = new(
14 "MY002",
15 Severity.Error,
16 $"The '{nameof(OnChange)}()' method must be have the 'protected' accessibility." );
17
Metalama requires the DiagnosticDefinition to be defined in a static field or property. To learn more about reporting errors, see Reporting and suppressing diagnostics.
Then, we add this code to the BuildAspect
method:
21// Implement the ISwitchableChangeTracking interface.
22var implementInterfaceResult = builder.Advice.ImplementInterface(
23 builder.Target,
24 typeof(ISwitchableChangeTracking),
25 OverrideStrategy.Ignore );
26
27// If the type already implements IChangeTracking, it must have a protected method called OnChanged, without parameters, otherwise
28// this is a contract violation, so we report an error.
29if ( implementInterfaceResult.Outcome == AdviceOutcome.Ignore )
30{
31 var onChangeMethod = builder.Target.AllMethods.OfName( nameof(this.OnChange) )
32 .SingleOrDefault( m => m.Parameters.Count == 0 );
33
34 if ( onChangeMethod == null )
35 {
36 builder.Diagnostics.Report( _mustHaveOnChangeMethod.WithArguments( builder.Target ) );
37 }
38 else if ( onChangeMethod.Accessibility != Accessibility.Protected )
39 {
40 builder.Diagnostics.Report( _onChangeMethodMustBeProtected );
41 }
42}
43
As in the previous step, the BuildAspect
method
calls ImplementInterface with
the Ignore
OverrideStrategy. This time, we inspect the outcome
of ImplementInterface. If the outcome is Ignored
, it means that
the
type or any base type already implements the IChangeTracking interface. In this case, we
check that the type contains a parameterless method named OnChange
and verify its accessibility.
Summary
This article explained how to report an error when the source code does not meet the expectations of the aspect. To make our aspect usable in practice, i.e., to make it possible to enable or disable a hypothetical Save button when the user performs changes in the UI, we still have to integrate with the INotifyPropertyChanged interface and raise the PropertyChanged event when the IsChanged property changes. We will see how to do this in the following article.