Skip to content

feat: generate fluent builders for codegen model DTOs (#415) - #429

Merged
AndreasIgel merged 89 commits into
java-helpers:mainfrom
igel-devin-ai:feat/issue-415-codegen-dto-builders
Nov 30, 2026
Merged

AndreasIgel merged 89 commits into
java-helpers:mainfrom
igel-devin-ai:feat/issue-415-codegen-dto-builders

Conversation

@igel-devin-ai

@igel-devin-ai igel-devin-ai commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Closes #415.

Adds fluent builders for the 12 public codegen model DTOs: GenerationTargetClassDto, ClassFieldDto, MethodDto, MethodParameterDto, MethodCodeDto, ConstructorDto, CodeTemplateDto, AnnotationDto, JavadocDto, JavadocCodeBlockDto, NestedTypeDto, GenericParameterDto. Builders are also added for the processor DTOs BuilderFieldDto, GetterInfoDto, BuilderMethodDto and BuilderNestedTypeDto.

  • How the builders are made: they were generated once with the project's own annotation processor and are committed next to the DTOs. Since then they are maintained by hand: there is no regeneration command and no CI drift check.
  • No dependency on simple-builders-core: the runtime classes the builders need (TrackedValue, IBuilderBase, the collection builders, …) are copied into org.javahelpers.codegen.builders.
  • Collection setters: every collection property that only had getX() + addX(...) now also has setX(List/Set/Map).
    • The setters copy the input, so there is no aliasing.
    • null throws NullPointerException before any state changes, and an empty collection clears the property.
    • addX is kept.
  • Replace vs. add in the builders: a method named after the property replaces the whole collection: classFields(List) or classFields(() -> list). The add2… methods add elements, including the overloads that configure the new element through its builder: add2ClassFields(f -> f.fieldName("x")) or add2ClassFields(f -> …, f -> …).
  • JavadocDtoBuilder: built on the description property: description(String) is literal, and description(format, args) formats exactly once. JavadocDto gets a setDescription(String) for this; the formatting constructor is kept for existing callers.
  • Primitive suppliers: boolean and int properties take BooleanSupplier / IntSupplier instead of Supplier<Boolean> / Supplier<Integer> (Sonar java:S4276). The generator itself is tracked in Generate primitive functional interfaces (BooleanSupplier, IntSupplier, …) for primitive fields #449.
  • Showcase: ShowcaseGenerationTest in codegen-roaster builds a complete class in one fluent chain: Javadoc, an annotation, fields, a constructor with a code template and a getter. It renders the class and asserts the full source, so it doubles as a usage example for consuming projects.
  • Tests:
    • CodegenDtoBuildersTest covers every builder with exact assertions on the built state, plus copying, empty, self-assignment and null behaviour for all new setters.
    • GenerationTargetClassDtoBuilderTest and ProcessorDtoBuildersTest cover the difference between adding and replacing.
    • Existing tests were moved from setter sequences to the builders, which is what the issue asked for.

Dependencies

The committed builders were generated with the processor code from these PRs, which are merged into this branch:

Tradeoffs (deliberately kept)

  • Builders maintained by hand instead of regenerated: this avoids a dependency on simple-builders-core and a bootstrap cycle. The cost is that improvements to the generator don't reach these builders automatically.
  • add2 naming: it follows the existing simple-builders convention. Renaming it to addTo is planned in a separate PR.

Verified: mvn clean verify passes.

@codecov

codecov Bot commented Nov 22, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ All tests successful. No failed tests found.

📢 Thoughts on this report? Let us know!

…gen-dto-builders

# Conflicts:
#	codegen-core/src/main/java/org/javahelpers/codegen/model/type/TypeNameGeneric.java
#	codegen-core/src/main/java/org/javahelpers/codegen/model/type/TypeNameWildcard.java
#	codegen-core/src/test/java/org/javahelpers/codegen/util/ImportCollectorTest.java
#	codegen-roaster/src/main/java/org/javahelpers/codegen/roaster/RoasterMapper.java
#	codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterCodeGeneratorTest.java
#	codegen-roaster/src/test/java/org/javahelpers/codegen/roaster/RoasterMapperTest.java
#	processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/AddToCollectionGenerator.java
#	processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/FieldInstanceConsumerGenerator.java
#	processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/ListConsumerGenerator.java
#	processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/MapConsumerGenerator.java
#	processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/NestedBuilderConsumerGenerator.java
#	processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/OptionalHelperGenerator.java
#	processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/SetConsumerGenerator.java
#	processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/VarArgsHelperGenerator.java
#	processor/src/main/java/org/javahelpers/simple/builders/processor/model/core/BuilderFieldDto.java
#	processor/src/main/java/org/javahelpers/simple/builders/processor/processing/BuilderDefinitionCreator.java
#	processor/src/test/java/org/javahelpers/simple/builders/processor/ReservedPropertyNameTest.java
#	simple-processor/src/main/java/org/javahelpers/codegen/analysis/JavaLangAnalyser.java
…core dep

- copy the 9 runtime classes the committed DTO builders need into
  org.javahelpers.codegen.builders.* (TrackedValue, IBuilderBase,
  BuilderImplementation, BuilderToStringStyle, the collection builders)
- remove the simple-builders-core dependency from codegen-core/pom.xml
- rewrite committed builders' imports to the copied classes
- move collection setters next to their add methods, enforce
  Objects.requireNonNull, keep the defensive copy (self-assignment safe)
- remove the codegen DTO builder drift check: CI step, regeneration
  test, and docs/CODEGEN_BUILDERS.md
…TO builders

The bootstrap builders don't need the generated-code markers; the copied
BuilderImplementation annotation is removed with them.
- add x(String packageName, String className) overloads next to the
  TypeName-typed setters (typeName, superType, fieldType,
  parameterTypeName, returnType, annotationType)
- GenerationTargetClassDtoBuilderTest: buildsWholeDtoInOneFluentStream
  builds a full GenerationTargetClassDto in one chain through the
  Consumer-based element-builder helpers
Each DTO now implements <X>DtoBuilder.With for copy-and-modify via
dto.with(b -> ...). CodeTemplateDto itself does not implement With so
MethodCodeDto/JavadocCodeBlockDto can take their own correctly typed
with() without unrelated-defaults conflicts.
…gen-dto-builders

# Conflicts:
#	codegen-core/src/main/java/org/javahelpers/codegen/util/JavadocExampleValues.java
#	processor/src/main/java/org/javahelpers/simple/builders/processor/generators/field/UpdateHelperGenerator.java
#	processor/src/main/java/org/javahelpers/simple/builders/processor/generators/util/MethodGeneratorUtil.java
BuilderFieldDtoBuilder, GetterInfoDtoBuilder, BuilderMethodDtoBuilder and
BuilderNestedTypeDtoBuilder generated with the annotation processor;
imports rewritten to the codegen-core builder helpers, @generated and
@BuilderImplementation stripped, DTOs implement the builder's With
interface. BuilderDefinitionDto intentionally excluded.
Each setter taking a TypeName (and the add2UpperBounds element method)
now offers a Class<?> variant delegating to TypeName.of(clazz), in both
the codegen DTO builders and the processor DTO builders.
Every TypeName setter now also offers xList/xSet/xArray/xGeneric/xMap
overloads in Class and TypeName argument variants, delegating to the
TypeName<X>.of factories (e.g. fieldTypeList(String.class)).
Every GenerationTargetClassDto (and nested DTO) in the tests is now built
in a single streamed builder chain via the committed *DtoBuilder classes,
using the Consumer-based element helpers and TypeName shortcuts
(fieldType("pkg", "Name"), parameterTypeNameArray, members(Map.of), ...).
No DTO is assembled via new + setter sequences anymore.
The processor module already depends on simple-builders-core, so its DTO
builders now use core's IBuilderBase, TrackedValue, BuilderToStringStyle
and collection helpers instead of the copied codegen classes. The two
element builders for codegen DTO types (GenericParameterDto, AnnotationDto)
are bridged via adapter classes that also implement core's IBuilderBase.
addAll already copies the elements, so the extra new ArrayList/LinkedHashSet
copy only guarded dto.setX(dto.getX()) self-assignment. A reference check
covers that without allocating; requireNonNull still runs first so a null
argument rejects without mutating state.
…Class), undo UpdateHelper streaming

- UpdateHelperGenerator: reverted to imperative javadoc example construction
- BuilderJavadocConstants: removed PARAM_TAG/RETURN_TAG duplicates of JavadocTag
- GenericParameterDtoBuilder: upperBounds(Class...) wholesale overload
- ClassFieldDtoBuilder: add2FieldTypeImports(pkg, name) overload
- BuilderDefinitionCreator: annotationType(SuppressWarnings.class), add2Members,
  add2FieldTypeImports(pkg, name)
- JacksonModuleGenerator: add2Members for builder member
- MethodGeneratorUtil: conditional() instead of ternary for parameter annotations
- sweep: parameterTypeName(String.class), upperBounds(X.class) across tests
…wildcard factory

Enhancers:
- WithInterfaceEnhancer: both with() methods as single streamed builder calls
  incl. methodCodeDto streaming and javadoc param/returns shortcuts
- CoreMethodsEnhancer: createBuildMethod uses builder variable with conditional
  Override annotation and streamed code/javadoc tail; createToStringMethod as
  one big streamed call
- GeneratedAnnotationEnhancer/BuilderImplementationAnnotationEnhancer:
  annotationType(Class) + add2Members
- JacksonAnnotationEnhancer: setterPrefix extracted, pkg/name annotationType,
  add2Members
- ConditionalEnhancer: misplaced ordering comment fixed
- ConstructorEnhancer: param shortcut

Builder additions:
- BuilderMethodDtoBuilder: methodCodeDto(Consumer/value) methods (build-time
  mapping existed already)
- GenericParameterDtoBuilder/MethodDtoBuilder: add2GenericsWithUpperBound /
  add2GenericParametersWithUpperBound for the common bounded case
- TypeNameWildcard.extendsBound(Class) factory

Tests/docs:
- RoasterCodeGeneratorTest: add2Annotations(Class), fieldTypeGeneric,
  returnTypeList, TypeNameList.of, upper-bounded generic shortcuts
- ShowcaseGenerationTest: class javadoc, returns shortcut
- ImportCollectorTest: shared bounded-wildcard constant at class end
- CUSTOMIZING.md samples: fully streamed incl. code templates with named
  placeholders and text blocks, StringUtils.capitalize, Void.class
- sweeps: add2Annotations(a -> a.annotationType(X.class)),
  annotationType(JavaLangMapper.map2TypeName(X.class)),
  add2Tags(new JavadocTagDto("return", x))
…md style

The doc samples and their compiling test mirrors now use the same streamed
API: methodCodeDto consumers with named placeholders, inline code()/build
chains, StringUtils.capitalize. Inner text blocks in test samples are
nested via escaped delimiters.
Removed the List/Set/Array/Generic/Map family (10 methods) from
GenericParameterDtoBuilder — upper bounds are plain types in practice,
and exotic cases remain expressible via add2UpperBounds(TypeName).
…da vars

- add2Parameters -> parameter, add2Methods -> method, add2ClassFields ->
  classField, add2Members -> member, add2Tags -> tag, add2UpperBounds ->
  upperBound, etc. across all committed DTO builders and every usage
- keyword collisions: add2Imports -> importStatement, add2Interfaces ->
  interfaceName (import/interface are reserved)
- verbose lambda parameters shortened (parameter -> p, method -> m, ...)
- generated-builder API expectations kept as add2X: that rename is java-helpers#443's
  scope, not this PR's
Comment thread docs/CUSTOMIZING.md Resolved
…e removal, fieldname placeholders

- MethodGeneratorUtil: conditional without false case (annotations default empty)
- docs+test: capitalize helpers removed, StringUtils.capitalize used inline
- validate sample: returnType(pkg,name), direct build return
- all samples: fieldname via named placeholder instead of formatted interpolation
- factory method: codeFormat with named argument
Comment thread docs/CUSTOMIZING.md Resolved
Comment thread docs/CUSTOMIZING.md Resolved
… formatting, method chaining

- GenerationTargetClassDtoBuilderTest/ProcessorDtoBuildersTest/samples: short lambda names (p/m/c/a/f)
- CodegenDtoBuildersTest: flat upperBound for single bound
- ImportCollectorTest: nested type construction broken into named variables with explanatory comment, constant moved to class top
- CUSTOMIZING.md+test: import indentation, empty lines, flattened parameter lambdas, date textblock linebreaks
- WithInterfaceEnhancer: chained .method() with per-method comments
- JacksonModuleGenerator/MethodGeneratorUtil: el -> a/p
- typeName(pkg, name) overload in JacksonModuleGenerator
- all .javadoc(JavadocDtoBuilder.create()...) sites converted to consumer style
- manual JavadocTagDto("return") replaced with .returns() shortcut
@sonarqubecloud

Copy link
Copy Markdown

@AndreasIgel
AndreasIgel merged commit 2dd7c20 into java-helpers:main Nov 30, 2026
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Builders for codegen model DTOs (GenerationTargetClassDto & friends)

4 participants