Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to efficiently create and use the builder pattern
    text
    copied!<p>On our last project we ended up with a shared test fixture for our unit tests which gave a lot of problems. So on our current project I've looked into the builder pattern. We run our unit tests in memory on the development machines and against the database on the build server.</p> <p>Currently I have a T4 template which produces for example the following builder for a Student:</p> <pre><code>public class StudentBuilder : Builder&lt;Student, StudentBuilder&gt; { public StudentBuilder() { IsMale = true; } public StudentBuilder WithFirstName(string firstName) { this.FirstName = firstName; return this; } public StudentBuilder WithLastName(string lastName) { this.LastName = lastName; return this; } public StudentBuilder WithIsMale(bool isMale) { this.IsMale = isMale; return this; } internal override Student Construct() { Student result = new Student() { FirstName = FirstName ?? "FirstName:" + id.ToString(), LastName = LastName ?? "LastName:" + id.ToString(), IsMale = IsMale, Id = id, }; / return result; } } </code></pre> <p>Trough the base classes I can use this in the following way:</p> <pre><code>Student wouter = StudentBuilder.Build() .WithFirstName("Wouter") .WithLastName("de Kort"); List&lt;Student&gt; students = StudentBuilder.Build().Multiple(10, (builder, index) =&gt; builder.WithFirstName("FirstName" + index)); </code></pre> <p>We run integration tests on our build server to make sure everything works against the database. This means we have to make sure that all referential constrains are met. But then the problems begin.</p> <p>For example, a student is required to have a mentor, a mentor belongs to a school, a school to a city, a city to a ....</p> <p>This would result in code like:</p> <pre><code>StudentBuilder.Build().WithMentor(MentorBuilder.Build().WithSchool(SchoolBuilder.Build().WithCity(CityBuilder.Build())) </code></pre> <p>How should I optimize this? I've thought about doing the 'default building' in the Construct method of each Builder but if I would build 10 students then it would lead to 10 mentors in 10 schools in 10 cities in 10....</p> <p>Or maybe creating methods like WithAllCity(..), WithAll(School)</p> <p>Any ideas? Am I actually using the Builder Pattern the right way? Could a Director class help? Or should I have inherited classes from StudentBuilder which solve these different cases?</p> <p>Or another idea, should I add more validation in my service layer before sending the data to the database? Then I would catch more errors in my unit tests against the in memory database.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload