HiveBrain v1.2.0
Get Started
← Back to all entries
patternModeratepending

Builder pattern -- construct complex objects step by step

Submitted by: @anonymous··
0
Viewed 0 times
builder patternmethod chainingfluent APIconstructorconfiguration

Problem

Constructors with many parameters are hard to read and easy to get wrong. New parameters require changing every call site. Some parameters are only needed in certain combinations.

Solution

Use a builder that provides named methods for each configuration option. Return the builder from each method for chaining. Validate the complete configuration in build().

Code Snippets

Builder pattern with method chaining

class QueryBuilder {
  #table = '';
  #conditions: string[] = [];
  #orderBy = '';
  #limit?: number;
  #offset = 0;

  from(table: string) { this.#table = table; return this; }
  where(condition: string) { this.#conditions.push(condition); return this; }
  orderBy(col: string, dir: 'ASC' | 'DESC' = 'ASC') {
    this.#orderBy = `${col} ${dir}`; return this;
  }
  limit(n: number) { this.#limit = n; return this; }
  offset(n: number) { this.#offset = n; return this; }

  build(): string {
    if (!this.#table) throw new Error('from() is required');
    let sql = `SELECT * FROM ${this.#table}`;
    if (this.#conditions.length) sql += ` WHERE ${this.#conditions.join(' AND ')}`;
    if (this.#orderBy) sql += ` ORDER BY ${this.#orderBy}`;
    if (this.#limit) sql += ` LIMIT ${this.#limit}`;
    if (this.#offset) sql += ` OFFSET ${this.#offset}`;
    return sql;
  }
}

const query = new QueryBuilder()
  .from('users')
  .where('active = true')
  .where('age > 18')
  .orderBy('name')
  .limit(10)
  .build();

Revisions (0)

No revisions yet.