The user wants me to design a "builder pattern lint."
The lint should focus on three specific areas:
- Construction Safety: Ensuring the object is built correctly and not in an invalid state.
- Dependency Injection (DI): How the builder interacts with DI frameworks or manual DI.
- Test Seams: How the builder pattern facilitates or hinders testing.
This sounds like a request for a static analysis rule (a lint), perhaps for a language like Java or C#, where the Builder pattern is common. I should structure the response as a proposal for a linting tool or a set of rules to be implemented in a linter (like an Error Prone check, a SonarQube rule, or an ESLint plugin for TypeScript).
1. Deconstructing the Request:
- Target: A linting rule (or set of rules) regarding the Builder Pattern.
- Key Themes:
- Construction Safety: Immutability, required fields, valid state upon
build().
- Dependency Injection (DI): Framework integration (Spring, Guice, Dagger) vs. manual wiring. Preventing "partial" injection or mixing framework concerns with POJO builders incorrectly.
- Test Seams: Mocking, faking, and the ability to inject test data/dependencies easily.
2. Structuring the Proposal:
I should organize this as if I were writing a spec for a tool like ArchUnit, Error Prone, or a custom Roslyn Analyzer.
- Title: Catchy name (e.g., "SafeBuilderLint").
- Philosophy: Why this matters (Fluent APIs are nice, but runtime exceptions are not).
- Rule Categories:
- Safety Rules (The "Must Haves"): Required fields, state consistency.
- DI Rules (The "Wiring"): Spring/JavaX integration, avoiding circular deps or half-baked beans.
- Testability Rules (The "Seams"): Visibility, setters vs. constructor.
3. Fleshing out the Rules (Iterative refinement):
4. Drafting the Content (Simulating the design process):
- Tone: Technical, prescriptive, architectural.
- Format: Rule Name -> Problem -> Solution -> Code Example (Bad vs Good).
Drafting Rule 1: The "Phantom Build" (Safety)
Problem: build() returns an object with null required fields.
Detection: Field f in TargetClass is non-null. Builder.setF is never called before build() (Data flow analysis is hard for linters, simpler check: does build() check nulls?).
Better approach for a lint: Enforce that build() checks Objects.requireNonNull for non-optional fields.
Drafting Rule 2: The "DI Breach" (DI)
Problem: Using a Builder to circumvent the DI container scope.
Context: Spring.
Scenario: You new Builder().build() a @Service.
Lint: "Manual construction of managed beans." If a class is annotated @Component/@Service, it should not be instantiated via a Builder manually (usually).
Drafting Rule 3: The "Mock blocker" (Testing)
Problem: Building concrete classes makes mocking hard.
Lint: "Concrete Return Type." The build() method should return an interface if the object is complex, to allow substituting a mock implementation.
5. Refining the "Construction Safety" (Advanced):
The "Type-Safe Builder" pattern (using generics or states) is a compile-time solution. A Lint is for runtime-risk or code-smell detection when type-state isn't used.
Let's focus on "Runtime Safety vs Lint Warning".
Rule: @RequiredArgs check. If using Lombok @Builder, are all mandatory fields actually marked?
6. Final Polish:
I will structure this as a technical specification for a static analysis tool.
I'll break it down into the three requested pillars.
I will provide "Severity" levels (Error, Warning, Info).
Self-Correction during drafting: The user asked for "Design a builder pattern lint". This implies defining what the lint checks. I need to be specific about the logic of the check.
- Safety: Check for uninitialized non-null fields in the
build() method.
- DI: Check that Builders don't hold state that belongs to a singleton scope if they are used as singletons themselves. Or, check that Builders aren't injected directly if they aren't thread-safe. Actually, a common DI anti-pattern is injecting a Builder to create prototypes.
- Test Seams: Verify that the
Builder allows overriding package-private or protected fields for test fixtures.
7. Final Structure:
- Overview: The "Why".
- Rule Set 1: Structural Integrity (Safety) - Focus on nullability and immutability.
- Rule Set 2: Dependency Hygiene (DI) - Focus on framework integration.
- Rule Set 3: Testing Observability - Focus on seams and mocks.
- Implementation Hint: How to build it (AST analysis).
Let's write it out. I will use Java/Kotlin terminology as it's the most common context for this, but keep it general enough.
Specific DI nuance: A builder is great for manual DI. It is often an anti-pattern for framework DI (Spring). If I have a UserBuilder, I probably don't want Spring to manage it. If I have a ServiceBuilder, I definitely do want Spring to manage the dependencies.
Lint: If a Builder takes @Autowired arguments, it shouldn't expose setters for them (Separation of concerns).
Let's go with the "Architectural Lint" approach.
- Safety: The "Incomplete Build" check.
- DI: The "Hidden Dependency" check (Builder hides
new calls).
- Test Seams: The "Final Class" check (Builder returns final class, preventing mocking).
This looks solid. I will generate the response based on this structure.
Designing a lint for the Builder Pattern requires moving beyond simple style checks. We need to enforce semantic correctness to ensure the pattern actually delivers on its promises: safety from invalid state, decoupling from infrastructure, and testability.
Here is a specification for BuilderGuard, a linting suite designed to enforce construction safety, dependency injection hygiene, and test seams.
1. Construction Safety (Integrity)
The primary goal of the Builder pattern is to prevent the construction of invalid objects (e.g., a User without an ID).
Rule: MandatoryFieldEnforcement
Problem: Developers often create builders that allow build() to be called without setting required fields, resulting in runtime NullPointerExceptions or default “zero” values that crash the system later.
Lint Logic:
- Identify the target class (the class being built).
- Identify fields in the target class that are
final (Java), readonly (C#), or not nullable/optional.
- Analyze the
Builder.build() method.
- Trigger Error: If a mandatory field is not assigned within the
build() method scope (either via setter on the builder or passed to the target constructor).
Code Example (Violation):
class User {
final String id; // Mandatory
String name; // Optional
}
class UserBuilder {
// VIOLATION: build() creates User without setting 'id'.
public User build() {
return new User();
}
}
Rule: PhaseCollisionDetection
Problem: Builders often accumulate state. If a builder allows setting a field after build() has been called, it implies the builder holds a reference to a mutable object or encourages reuse of a "dirty" builder.
Lint Logic:
- Flag any invocation of a builder setter method (e.g.,
setName) that occurs strictly after an invocation of build() in the control flow graph, without an intervening new Builder() or reset().
2. Dependency Injection (DI) Hygiene
Builders are often used to wire dependencies. However, mixing business logic construction with infrastructure concerns creates "hidden" dependencies that DI containers cannot see.
Rule: HiddenInfrastructureDependency
Problem: A builder manually instantiates a heavy infrastructure dependency (like a Database Repository or API Client) inside the builder or the target class constructor, bypassing the DI container.
Lint Logic:
- Analyze the
build() method and the target class constructor.
- Trigger Warning: If
new is used to instantiate a class annotated with @Service, @Repository, @Component, or implementing specific interfaces (e.g., IDbConnection).
- Suggestion: These dependencies should be passed into the Builder’s constructor or a specific
inject() method.
Code Example (Violation):
class OrderBuilder {
public Order build() {
// VIOLATION: Bypassing DI container.
// Hard to mock in tests, hard to swap implementations.
PaymentService service = new StripeService();
return new Order(service);
}
}
Rule: ContextLeakage
Problem: In web frameworks (like Spring), passing the entire ApplicationContext into a builder to pull dependencies is an anti-pattern (Service Locator). It hides the actual dependencies of the class.
Lint Logic:
- Detect method signatures in the Builder or Target Class that accept
ApplicationContext, Container, or Environment types.
- Trigger Error: "Service Locator anti-pattern detected. Explicitly inject required dependencies."
3. Test Seams (Mockability)
The Builder pattern should facilitate testing by allowing the injection of mocks or fakes.
Rule: ConcreteReturnCoupling
Problem: If the build() method returns a concrete class rather than an interface, tests cannot easily swap the object for a mock or stub. This happens frequently when builders are used to create complex domain objects that should actually be abstracted behind interfaces.
Lint Logic:
- Check the return type of
Builder.build().
- Trigger Warning: If the return type is a
final class or a class with no interface implementation, and that class performs I/O (network/DB) operations (detected via method analysis).
Rule: TestOnlyVisibility
Problem: Sometimes developers add setters to the target class solely so the builder can set private fields. This breaks encapsulation by allowing direct mutation of the object after construction.
Lint Logic:
- Identify private fields in the Target Class.
- Check if there are public setters for these fields that are only called by the Builder.
- Suggestion: Remove public setters. Use Reflection in the Builder (or language features like package-private access) to set fields, ensuring the object is immutable to the rest of the production code.
Summary of Lint Configuration
| Rule Name | Severity | Category | Description |
|---|
MissingRequiredField | Error | Safety | build() invoked without setting non-nullable fields. |
ServiceLocatorInBuilder | Warning | DI | Builder accepts a generic DI Context/Container. |
HardcodedDependency | Warning | DI | Builder news up an infrastructure class (Repo/Service). |
BuilderStateReuse | Info | Safety | Builder method called after build() without reset. |
ConcreteBuildReturn | Info | Test | build() returns a concrete class, preventing polymorphic mocking. |
Implementation Hint (for Java/Kotlin)
This can be implemented as a Java AST Walker (e.g., using Spoon or Checkstyle):
- AST Traversal: Find classes ending in
Builder.
- Symbol Resolution: Link the builder to its return type.
- Data Flow: Ensure all
final fields in the return type have a definition reaching the return statement in the build() method.