Open sandboxFocusImprove this doc

Builder example, step 1: getting started

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 the Builder, calling the Validate method if present.
  • Add the following members to the source type:
    • A private constructor called by the Builder.Build method.
    • A ToBuilder method returning a new Builder initialized with the current instance.

Here's an illustration of the changes performed by this aspect when applied to a simple class:

Source Code
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}
Transformed Code
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.

13public override void BuildAspect( IAspectBuilder<INamedType> builder )
14{
15    base.BuildAspect( builder );
16
17    var sourceType = builder.Target;
18
19    // Create a list of PropertyMapping items for all properties that we want to build using the Builder.
20    var properties = sourceType.Properties.Where( p => p.Writeability != Writeability.None &&
21                                                       !p.IsStatic )
22        .Select( p => new PropertyMapping(
23                     p,
24                     p.Attributes.OfAttributeType( typeof(RequiredAttribute) ).Any() ) )
25        .ToList();
26

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:

137builder.Tags = new Tags(
138    builder.Target,
139    properties,
140    sourceConstructor,
141    builderCopyConstructor );
142

2. Creating the Builder type and the properties

Let's now create a nested type using IntroduceClass:

30// Introduce the Builder nested type.
31var builderType = builder.IntroduceClass(
32    "Builder",
33    buildType: t => t.Accessibility = Accessibility.Public );
34

For details about creating new types, see Introducing types.

Introducing properties is straightforward, as described in Introducing members:

38// Add builder properties and update the mapping.
39foreach ( var property in properties )
40{
41    property.BuilderProperty =
42        builderType.IntroduceAutomaticProperty(
43                property.SourceProperty.Name,
44                property.SourceProperty.Type,
45                buildProperty: p =>
46                {
47                    p.Accessibility = Accessibility.Public;
48                    p.InitializerExpression = property.SourceProperty.InitializerExpression;
49                } )
50            .Declaration;
51}
52

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.

56// Add a builder constructor accepting the required properties and update the mapping.
57builderType.IntroduceConstructor(
58    nameof(this.BuilderConstructorTemplate),
59    buildConstructor: c =>
60    {
61        c.Accessibility = Accessibility.Public;
62
63        foreach ( var property in properties.Where( m => m.IsRequired ) )
64        {
65            var parameter = c.AddParameter(
66                NameHelper.ToParameterName( property.SourceProperty.Name ),
67                property.SourceProperty.Type );
68
69            property.BuilderConstructorParameterIndex = parameter.Index;
70        }
71    } );
72

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.

147[Template]
148private void BuilderConstructorTemplate()
149{
150    var tags = (Tags) meta.Tags.Source!;
151
152    foreach ( var property in tags.Properties.Where( p => p.IsRequired ) )
153    {
154        property.BuilderProperty!.Value =
155            meta.Target.Parameters[property.BuilderConstructorParameterIndex!.Value].Value;
156    }
157}
158

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:

76// Add a constructor to the source type with all properties.
77var sourceConstructor = builder.IntroduceConstructor(
78        nameof(this.SourceConstructorTemplate),
79        buildConstructor: c =>
80        {
81            c.Accessibility = Accessibility.Private;
82
83            foreach ( var property in properties )
84            {
85                var parameter = c.AddParameter(
86                    NameHelper.ToParameterName( property.SourceProperty.Name ),
87                    property.SourceProperty.Type );
88
89                property.SourceConstructorParameterIndex = parameter.Index;
90            }
91        } )
92    .Declaration;
93

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.

174[Template]
175private void SourceConstructorTemplate()
176{
177    var tags = (Tags) meta.Tags.Source!;
178
179    foreach ( var property in tags.Properties )
180    {
181        property.SourceProperty.Value =
182            meta.Target.Parameters[property.SourceConstructorParameterIndex!.Value].Value;
183    }
184}
185

Equipped with this constructor, we can now introduce the Build method:

97// Add a Build method to the builder.
98builderType.IntroduceMethod(
99    nameof(this.BuildMethodTemplate),
100    IntroductionScope.Instance,
101    buildMethod: m =>
102    {
103        m.Name = "Build";
104        m.Accessibility = Accessibility.Public;
105        m.ReturnType = sourceType;
106    } );
107

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.

187
189[Template]
190private dynamic BuildMethodTemplate()
191{
192    var tags = (Tags) meta.Tags.Source!;
193
194    // Build the object.
195    var instance = tags.SourceConstructor.Invoke( tags.Properties.Select( x => x.BuilderProperty! ) )!;
196
197    // Find and invoke the Validate method, if any.
198    var validateMethod = tags.SourceType.AllMethods.OfName( "Validate" )
199        .SingleOrDefault( m => m.Parameters.Count == 0 );
200
201    if ( validateMethod != null )
202    {
203        validateMethod.WithObject( (IExpression) instance ).Invoke();
204    }
205
206    // Return the object.
207    return instance;
208}
209

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:

111// Add a builder constructor that creates a copy from the source type.
112var builderCopyConstructor = builderType.IntroduceConstructor(
113        nameof(this.BuilderCopyConstructorTemplate),
114        buildConstructor: c =>
115        {
116            c.Accessibility = Accessibility.Internal;
117            c.Parameters[0].Type = sourceType;
118        } )
119    .Declaration;
120

Unsurprisingly, the template of this constructor just goes through the list of PropertyMapping and assigns the Builder properties from the corresponding source properties:

160
161[Template]
162private void BuilderCopyConstructorTemplate( dynamic source )
163{
164    var tags = (Tags) meta.Tags.Source!;
165
166    foreach ( var property in tags.Properties )
167    {
168        property.BuilderProperty!.Value =
169            property.SourceProperty.WithObject( (IExpression) source ).Value;
170    }
171}
172

We can finally introduce the ToBuilder method:

124// Add a ToBuilder method to the source type.
125builder.IntroduceMethod(
126    nameof(this.ToBuilderMethodTemplate),
127    buildMethod: m =>
128    {
129        m.Accessibility = Accessibility.Public;
130        m.Name = "ToBuilder";
131        m.ReturnType = builderType.Declaration;
132    } );
133

Here is the template for the constructor body. It only invokes the constructor.

211
212[Template]
213private dynamic ToBuilderMethodTemplate()
214{
215    var tags = (Tags) meta.Tags.Source!;
216
217    return tags.BuilderCopyConstructor.Invoke( meta.This );
218}

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.