</>CodexBash
All articles
Programming

The builder pattern

The builder pattern for objects with many optional parameters: the telescoping-constructor problem it solves, a complete Java builder with validation, immutability, Lombok and records, the Python equivalent, and when a builder is overkill.

CodexBash, , 4 min read

Some objects need a lot of settings to create: an HTTP request has a URL, a method, headers, a body, a timeout and retry rules, most of them optional. Writing constructors for every combination quickly gets unreadable, and a call like new Request(url, "GET", null, null, 30, 3, true) tells the reader nothing. The builder pattern solves this by letting you set each value by name, in any order, and then build a finished, valid object in one step. This article shows the problem, a complete Java builder, and the alternatives.

Sign in to read the rest

The whole 4 minute article is free with an account, along with every problem, lesson and tutorial. No card.