To create our test data, we use the following variation of the Builder pattern (simplified example!):
Sample class:
public class Person
{
public string Name { get; set; }
public string Country { get; set; }
}
The builder:
public class PersonBuilder
{
private string name;
private string country;
public PersonBuilder()
{
SetDefaultValues();
}
private void SetDefaultValues()
{
name = "TODO";
country = "TODO";
}
public Person Build()
{
return new Person
{
Name = name,
Country = country
};
}
public PersonBuilder WithName(string name)
{
this.name = name;
return this;
}
public PersonBuilder WithCountry(string country)
{
this.country = country;
return this;
}
}
NOTE: The context of the example itself is not relevant. The important thing here is how in the example, the a builder class like PersonBuilder can completely be generated by looking at the entity class (Person) and applying the same pattern - see below.
Now imagine that the person class has 15 properties instead of 2. It would take some monkeywork to implement the builder class, while theoretically, it could automatically be generated from the Person class. We could use code generation to quickly set up the builder class, and add custom code later if needed.
The code generation process would have to be aware of the context (name and properties of the person class), so simple text-based code generation or regex magic doesn't feel right here. A solution that is dynamic, not text-based and can be triggered quickly from inside visual studio is preferred.
I'm looking for the best way to perform code generation for scenarios like this. Reflection? Codesmith? T4 templates? Resharper Live templates with macros?
I'm looking forward to see some great answers :)