Practice ยท 3 of 4
Builder: Valid Orders Only
OrderReq has required fields and derived invariants that are too
easy to get wrong by hand. Build a **Builder** whose Build() enforces them
or throws:
- WithCustomer(string) โ required, non-empty; Build() throws if missing
- WithItem(string sku, int qty, decimal price) โ repeatable; qty must be
โฅ 1 (throw ArgumentException in WithItem itself)
- WithRush() โ flags rush delivery
- Build() throws when: no customer, no items, or a rush order with more
than 10 total items (business rule)
Expose the built fields the tests read: Customer, TotalQty, Items
(count), Rush.
``csharp
public static class Solution
{
public sealed class OrderReq { public string Customer = ""; public int TotalQty; public int Items; public bool Rush; }
public sealed class OrderBuilder
{
public OrderBuilder WithCustomer(string c);
public OrderBuilder WithItem(string sku, int qty, decimal price); // qty >= 1
public OrderBuilder WithRush();
public OrderReq Build(); // enforces invariants
}
}
``
Back to lesson: Practice: Patterns Practice: Strategy, Decorator, Builder