In this first article, we aim to implement the initial working version of the Builder pattern as described in the parent article. However, we'll ignore two important features for now: class inheritance and immutable collections.
Our goal is to write an aspect that will perform the following transformations:
- Introduce a nested class named
Builder
with the following members:- A copy constructor initializing the
Builder
class from an instance of the source class. - A public constructor for users of our class, accepting values for all required properties.
- A writable property for each property of the source type.
- A
Build
method that instantiates the source type with the values set in theBuilder
, calling theValidate
method if present.
- A copy constructor initializing the
- Add the following members to the source type:
- A private constructor called by the
Builder.Build
method. - A
ToBuilder
method returning a newBuilder
initialized with the current instance.
- A private constructor called by the
Here's an illustration of the changes performed by this aspect when applied to a simple class:
1using System.ComponentModel.DataAnnotations;
2
3namespace Metalama.Samples.Builder1.Tests.SimpleExample;
4
5[GenerateBuilder]
6public partial class Song
7{
8 [Required]
9 public string Artist { get; }
10
11 [Required]
12 public string Title { get; }
13
14 public TimeSpan? Duration { get; }
15
16 public string Genre { get; } = "General";
17}
1using System.ComponentModel.DataAnnotations;
2
3namespace Metalama.Samples.Builder1.Tests.SimpleExample;
4
5[GenerateBuilder]
6public partial class Song
7{
8 [Required]
9 public string Artist { get; }
10
11 [Required]
12 public string Title { get; }
13
14 public TimeSpan? Duration { get; }
15
16 public string Genre { get; } = "General";
17
18 private Song(string artist, string title, TimeSpan? duration, string genre)
19 {
20 Artist = artist;
21 Title = title;
22 Duration = duration;
23 Genre = genre;
24 }
25
26 public Builder ToBuilder()
27 {
28 return new Builder(this);
29 }
30
31 public class Builder
32 {
33 public Builder(string artist, string title)
34 {
35 Artist = artist;
36 Title = title;
37 }
38
39 internal Builder(Song source)
40 {
41 Artist = source.Artist;
42 Title = source.Title;
43 Duration = source.Duration;
44 Genre = source.Genre;
45 }
46
47 private string _artist = default!;
48
49 public string Artist
50 {
51 get
52 {
53 return _artist;
54 }
55
56 set
57 {
58 _artist = value;
59 }
60 }
61
62 private TimeSpan? _duration;
63
64 public TimeSpan? Duration
65 {
66 get
67 {
68 return _duration;
69 }
70
71 set
72 {
73 _duration = value;
74 }
75 }
76
77 private string _genre = "General";
78
79 public string Genre
80 {
81 get
82 {
83 return _genre;
84 }
85
86 set
87 {
88 _genre = value;
89 }
90 }
91
92 private string _title = default!;
93
94 public string Title
95 {
96 get
97 {
98 return _title;
99 }
100
101 set
102 {
103 _title = value;
104 }
105 }
106
107 public Song Build()
108 {
109 var instance = new Song(Artist, Title, Duration, Genre);
110 return instance;
111 }
112 }
113}
1. Setting up the infrastructure
We are about to author complex aspects that introduce members with relationships to each other. Before diving in, a bit of planning and infrastructure is necessary.
It's good practice to keep the T# template logic simple and do the hard work in the BuildAspect method. The question is how to pass data from BuildAspect
to T# templates. As explained in Sharing state with advice, a convenient approach is to use tags. Since we will have many tags, it's even more convenient to use strongly-typed tags containing all the data that BuildAspect
needs to pass to templates. This is the purpose of the Tags
record.
A critical member of the Tags
record is a collection of PropertyMapping
objects. The PropertyMapping
class maps a source property to a Builder
property, as well as to the corresponding parameter in different constructors.
Here's the source code for the Tags
and PropertyMapping
types:
9[CompileTime]
10private record Tags(
11 INamedType SourceType,
12 IReadOnlyList<PropertyMapping> Properties,
13 IConstructor SourceConstructor,
14 IConstructor BuilderCopyConstructor );
15
16[CompileTime]
17private class PropertyMapping
18{
19 public PropertyMapping( IProperty sourceProperty, bool isRequired )
20 {
21 this.SourceProperty = sourceProperty;
22 this.IsRequired = isRequired;
23 }
24
25 public IProperty SourceProperty { get; }
26
27 public bool IsRequired { get; }
28
29 public IProperty? BuilderProperty { get; set; }
30
31 public int? SourceConstructorParameterIndex { get; set; }
32
33 public int? BuilderConstructorParameterIndex { get; set; }
34}
35
The first thing we do in the BuildAspect
method is build a list of properties. When we initialize this list, we don't yet know all data items because they haven't been created yet.
14public override void BuildAspect( IAspectBuilder<INamedType> builder )
15{
16 base.BuildAspect( builder );
17
18 var sourceType = builder.Target;
19
20 // Create a list of PropertyMapping items for all properties that we want to build using the Builder.
21 var properties = sourceType.Properties.Where(
22 p => p.Writeability != Writeability.None &&
23 !p.IsStatic )
24 .Select(
25 p => new PropertyMapping(
26 p,
27 p.Attributes.OfAttributeType( typeof(RequiredAttribute) ).Any() ) )
28 .ToList();
29
As you can see, we use the RequiredAttribute custom attribute to determine if a property is required or optional. We chose not to use the required
keyword because required
properties cannot be initialized from the constructor, making code generation more cumbersome for a first example.
Spoiler alert: here's how we share the Tags
class with advice at the end of the BuildAspect
method:
140builder.Tags = new Tags(
141 builder.Target,
142 properties,
143 sourceConstructor,
144 builderCopyConstructor );
145
2. Creating the Builder type and the properties
Let's now create a nested type using IntroduceClass:
33// Introduce the Builder nested type.
34var builderType = builder.IntroduceClass(
35 "Builder",
36 buildType: t => t.Accessibility = Accessibility.Public );
37
For details about creating new types, see Introducing types.
Introducing properties is straightforward, as described in Introducing members:
41// Add builder properties and update the mapping.
42foreach ( var property in properties )
43{
44 property.BuilderProperty =
45 builderType.IntroduceAutomaticProperty(
46 property.SourceProperty.Name,
47 property.SourceProperty.Type,
48 buildProperty: p =>
49 {
50 p.Accessibility = Accessibility.Public;
51 p.InitializerExpression = property.SourceProperty.InitializerExpression;
52 } )
53 .Declaration;
54}
55
Note that we copy the InitializerExpression
(i.e., the expression to the right of the =
sign on an automatic property) from the source property to the builder property. This ensures that these properties will have the proper default value, even in the Builder
class.
The created property is then stored in the BuilderProperty
property of the PropertyMapping
object, so we can refer to it later.
3. Creating the Builder public constructor
Our next task is to create the public constructor of the Builder
nested type, which should have parameters for all required properties.
59// Add a builder constructor accepting the required properties and update the mapping.
60builderType.IntroduceConstructor(
61 nameof(this.BuilderConstructorTemplate),
62 buildConstructor: c =>
63 {
64 c.Accessibility = Accessibility.Public;
65
66 foreach ( var property in properties.Where( m => m.IsRequired ) )
67 {
68 var parameter = c.AddParameter(
69 NameHelper.ToParameterName( property.SourceProperty.Name ),
70 property.SourceProperty.Type );
71
72 property.BuilderConstructorParameterIndex = parameter.Index;
73 }
74 } );
75
We use the AddParameter method to dynamically create a parameter for each required property. We save the ordinal of this parameter in the BuilderConstructorParameterIndex
property of the PropertyMapping
object for later reference in the constructor implementation.
Here is BuilderConstructorTemplate
, the template for this constructor. You can now see how we use the Tags
and PropertyMapping
objects. This code iterates through required properties and assigns a property of the Builder
type to the value of the corresponding constructor parameter.
150[Template]
151private void BuilderConstructorTemplate()
152{
153 var tags = (Tags) meta.Tags.Source!;
154
155 foreach ( var property in tags.Properties.Where( p => p.IsRequired ) )
156 {
157 property.BuilderProperty!.Value =
158 meta.Target.Parameters[property.BuilderConstructorParameterIndex!.Value].Value;
159 }
160}
161
4. Implementing the Build method
The Build
method of the Builder
type is responsible for creating an instance of the source (immutable) type from the values of the Builder
.
It requires a new constructor in the source type accepting a parameter for all properties. Here's how to create it:
79// Add a constructor to the source type with all properties.
80var sourceConstructor = builder.IntroduceConstructor(
81 nameof(this.SourceConstructorTemplate),
82 buildConstructor: c =>
83 {
84 c.Accessibility = Accessibility.Private;
85
86 foreach ( var property in properties )
87 {
88 var parameter = c.AddParameter(
89 NameHelper.ToParameterName( property.SourceProperty.Name ),
90 property.SourceProperty.Type );
91
92 property.SourceConstructorParameterIndex = parameter.Index;
93 }
94 } )
95 .Declaration;
96
We store the resulting constructor in a local variable, so we can pass it to the Tags
object later in the BuildAspect
method.
The template for this constructor is SourceConstructorTemplate
. It simply assigns the properties based on constructor parameters.
177[Template]
178private void SourceConstructorTemplate()
179{
180 var tags = (Tags) meta.Tags.Source!;
181
182 foreach ( var property in tags.Properties )
183 {
184 property.SourceProperty.Value =
185 meta.Target.Parameters[property.SourceConstructorParameterIndex!.Value].Value;
186 }
187}
188
Equipped with this constructor, we can now introduce the Build
method:
100// Add a Build method to the builder.
101builderType.IntroduceMethod(
102 nameof(this.BuildMethodTemplate),
103 IntroductionScope.Instance,
104 buildMethod: m =>
105 {
106 m.Name = "Build";
107 m.Accessibility = Accessibility.Public;
108 m.ReturnType = sourceType;
109 } );
110
The T# template for the Build
method first invokes the newly introduced constructor, then tries to find and call the optional Validate
method before returning the new instance of the source type.
190
192[Template]
193private dynamic BuildMethodTemplate()
194{
195 var tags = (Tags) meta.Tags.Source!;
196
197 // Build the object.
198 var instance = tags.SourceConstructor.Invoke( tags.Properties.Select( x => x.BuilderProperty! ) )!;
199
200 // Find and invoke the Validate method, if any.
201 var validateMethod = tags.SourceType.AllMethods.OfName( "Validate" )
202 .SingleOrDefault( m => m.Parameters.Count == 0 );
203
204 if ( validateMethod != null )
205 {
206 validateMethod.With( (IExpression) instance ).Invoke();
207 }
208
209 // Return the object.
210 return instance;
211}
212
5. Implementing the ToBuilder method
Our last task is to add a ToBuilder
method to the source type, which must create an instance of the Builder
type initialized with the values of the current instance.
First, we'll need a new constructor in the Builder
type, called the copy constructor. In theory, we could reuse the public constructor for this purpose, but the next articles in this series will be simpler if we use a copy constructor here.
Let's add this code to BuildAspect
:
114// Add a builder constructor that creates a copy from the source type.
115var builderCopyConstructor = builderType.IntroduceConstructor(
116 nameof(this.BuilderCopyConstructorTemplate),
117 buildConstructor: c =>
118 {
119 c.Accessibility = Accessibility.Internal;
120 c.Parameters[0].Type = sourceType;
121 } )
122 .Declaration;
123
Unsurprisingly, the template of this constructor just goes through the list of PropertyMapping
and assigns the Builder
properties from the corresponding source properties:
163
164[Template]
165private void BuilderCopyConstructorTemplate( dynamic source )
166{
167 var tags = (Tags) meta.Tags.Source!;
168
169 foreach ( var property in tags.Properties )
170 {
171 property.BuilderProperty!.Value =
172 property.SourceProperty.With( (IExpression) source ).Value;
173 }
174}
175
We can finally introduce the ToBuilder
method:
127// Add a ToBuilder method to the source type.
128builder.IntroduceMethod(
129 nameof(this.ToBuilderMethodTemplate),
130 buildMethod: m =>
131 {
132 m.Accessibility = Accessibility.Public;
133 m.Name = "ToBuilder";
134 m.ReturnType = builderType.Declaration;
135 } );
136
Here is the template for the constructor body. It only invokes the constructor.
214
215[Template]
216private dynamic ToBuilderMethodTemplate()
217{
218 var tags = (Tags) meta.Tags.Source!;
219
220 return tags.BuilderCopyConstructor.Invoke( meta.This );
221}
Conclusion
As you can see, automating the Builder
aspect with Metalama can seem complex at the beginning, but the process can be split into individual simple tasks. It's crucial to start with proper analysis and planning. You should first know what you want and how exactly you want to transform the code. Once this is clear, the implementation becomes quite straightforward.
In the next article, we will see how to take type inheritance into account.