{
    "slug": "builder_pattern",
    "term": "Builder Pattern",
    "category": "quality",
    "difficulty": "intermediate",
    "short": "Constructs complex objects step-by-step using a fluent interface, separating construction from representation.",
    "long": "The Builder pattern addresses constructors with many parameters (especially optional ones) by providing a step-by-step construction API: $query = QueryBuilder::select('users')->where('active', true)->orderBy('name')->limit(10)->build(). Each setter returns $this (fluent interface), and build() returns the final immutable object. In PHP, Builders appear in query builders (Doctrine DBAL), HTTP client requests, and test fixture factories. Compared to long constructors or setters, Builders make invalid intermediate states visible and enable validation at build() time.",
    "aliases": [
        "builder",
        "fluent builder",
        "step builder"
    ],
    "tags": [
        "design-pattern",
        "oop",
        "creational"
    ],
    "misconception": "The builder pattern is just a verbose alternative to constructors. Builders enforce construction order, validate intermediate state, and make optional parameters explicit — they are most valuable when objects have many optional fields or complex construction rules.",
    "why_it_matters": "The Builder pattern constructs complex objects step by step, separating construction from representation — it eliminates telescoping constructors and makes optional parameters explicit.",
    "common_mistakes": [
        "Using a builder for simple objects with 2-3 parameters — a plain constructor or named arguments is cleaner.",
        "Not validating required fields in the build() method — the builder produces an invalid object silently.",
        "Forgetting to return $this from each setter — breaks the fluent chain.",
        "Reusing the same builder instance for multiple objects without resetting state between builds."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "factory_pattern",
        "fluent_interface",
        "value_object",
        "long_parameter_list"
    ],
    "prerequisites": [
        "fluent_builder",
        "constructor_promotion",
        "interfaces"
    ],
    "refs": [
        "https://refactoring.guru/design-patterns/builder"
    ],
    "bad_code": "// Telescoping constructor — hard to read and extend:\nfunction __construct(\n    string $name, ?string $email = null, ?string $phone = null,\n    ?string $address = null, bool $active = true, int $role = 1\n) {} // 6 params, optional ones hard to manage — use a builder",
    "good_code": "class QueryBuilder {\n    private array  $wheres  = [];\n    private ?int   $limit   = null;\n    private string $orderBy = 'id';\n\n    public function where(string $col, mixed $val): static {\n        $this->wheres[] = [$col, $val];\n        return $this;\n    }\n    public function limit(int $n): static {\n        $this->limit = $n;\n        return $this;\n    }\n    public function orderBy(string $col): static {\n        $this->orderBy = $col;\n        return $this;\n    }\n    public function build(): string { /* assemble SQL */ }\n}\n\n$sql = (new QueryBuilder())\n    ->where('status', 'active')\n    ->where('role', 'admin')\n    ->orderBy('created_at')\n    ->limit(10)\n    ->build();",
    "quick_fix": "Use a builder when constructing an object requires many optional parameters or multi-step configuration — it makes invalid states unrepresentable if you validate in build()",
    "severity": "low",
    "effort": "medium",
    "created": "2026-03-15",
    "updated": "2026-03-22",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/builder_pattern",
        "html_url": "https://codeclaritylab.com/glossary/builder_pattern",
        "json_url": "https://codeclaritylab.com/glossary/builder_pattern.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[Builder Pattern](https://codeclaritylab.com/glossary/builder_pattern) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/builder_pattern"
            }
        }
    }
}