When an object has many optional parameters or is built in steps.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | // ====================================================================== // Q: Builder pattern: when do you use it? // // When an object has many optional parameters or is built in steps. In .NET: // WebApplication.CreateBuilder(), StringBuilder, UriBuilder. In practice I use // it a lot in tests (Test Data Builder), like the OrderBuilder from Q20. // In the interview don't just name patterns. Say what problem it solved and when // you don't use it. A pattern without a reason to exist is over-engineering. // ====================================================================== // Test Data Builder public class OrderBuilder { private int _customerId = 1; private readonly List<(string Sku, int Qty)> _lines = []; public static OrderBuilder Draft() => new(); public OrderBuilder ForCustomer(int id) { _customerId = id; return this; } public OrderBuilder WithLine(string sku, int qty) { _lines.Add((sku, qty)); return this; } public Order Build() { var order = Order.Create(_customerId); foreach (var (sku, qty) in _lines) order.AddLine(sku, qty, new Money(10m, "EUR")); return order; // always valid, goes through the domain rules } } |