Skip to content

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

Open
igel-devin-ai wants to merge 32 commits into
java-helpers:mainfrom
igel-devin-ai:feat/issue-415-codegen-dto-builders
Open

igel-devin-ai wants to merge 32 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. They are generated by the project's own annotation processor and committed next to the DTOs.

  • Collection setters: every collection property that only had getX() + addX(...) now also has setX(List/Set), so the builders get collection methods: classFields, methods, constructors, generics, interfaces, nestedTypes, classAnnotations, imports, parameters, genericParameters, annotations, upperBounds, fieldTypeImports, members, tags, codeArguments, codeBlockImports. The setters copy the input (no aliasing). null throws NullPointerException before any state is changed, and an empty collection clears the property. addX is kept.
  • Regeneration and drift check: the commands are in docs/CODEGEN_BUILDERS.md. The Java CI workflow regenerates the builders and fails if git diff --exit-code finds a change, so a hand edit to a generated builder fails CI.
  • Tests: CodegenDtoBuildersTest covers all 12 builders with exact assertions on the built state. It also covers copying, empty, self-assignment and null behavior for all 22 new setters.
  • Existing tests were moved from setter sequences to the builders, which is the motivation of the issue.

Dependencies

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

Tradeoffs (deliberately kept)

  • codegen-core depends on simple-builders-core. The generated builders need its runtime types (IBuilderBase, TrackedValue, …). Kept because it is the cheapest way to dogfood the processor. The alternative is to move these runtime types into a neutral module. core builds first in the reactor, so there is no cycle.
  • Processor-internal DTOs (BuilderDefinitionDto & friends) are left out, which matches the issue's scope for a second step.

Verified: mvn clean verify and mvn -pl example clean compile pass.

@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
@sonarqubecloud

Copy link
Copy Markdown

…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)).
Comment thread codegen-core/pom.xml Resolved
Comment on lines +90 to +94
// Adding the type
if (type instanceof TypeNameWildcard wildcard) {
wildcard.getBound().ifPresent(this::addTypeImports);
return this;
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Where is this coming from? Did we have a bug here for these cases?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, that was a real bug this PR surfaced: for a wildcard type like ? extends Instant, addTypeImports called addImport(wildcard) which imported nothing — the bound type (Instant) was lost. Generic type args and array component types were already traversed inside addImport; the wildcard bound was the only missing case. Covered by convenienceImportMethodsTraverseWildcardBounds in ImportCollectorTest (target/field/code-block import paths).

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please create an issue (linked to the one which introduced wildcards) and a separate PR for this!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deep-check before splitting: the 4-line block is actually a no-op — addImport(TypeName) already unwraps TypeNameWildcard bounds since #436 (for #435), which is also why collectsWildcardBoundImportsInsteadOfWildcardTokens exists and passes on main. addTypeImports → addImport already recursed into the bound; my earlier "bound dropped" reading was wrong. So there's nothing real to fix — I reverted ImportCollector.java back to main's version instead of opening an issue + PR for a redundant change. If you'd still like a tracking issue (e.g. to simplify addTypeImports), say the word.

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.
…rtcuts, streamed tests

- Add setParameters/setGenericParameters/setAnnotations to BuilderMethodDto,
  setMethods/setAnnotations to BuilderNestedTypeDto, setMethods to BuilderFieldDto
  (requireNonNull + defensive copy/self-assignment safe, next to addX methods)
- Add full collection method suites to BuilderMethodDtoBuilder (parameters,
  genericParameters, annotations), BuilderNestedTypeDtoBuilder (methods,
  annotations) and BuilderFieldDtoBuilder (methods): add2X, varargs,
  Consumer<ArrayListBuilderWithElementBuilders>, Supplier, List and xUpdate,
  mirroring the codegen DTO builder optimizations
- Add nested element-builder adapters bridging codegen builders to the core
  IBuilderBase contract; BuilderMethodDtoBuilder used directly (already core)
- Add fieldType/returnType(String packageName, String className) overloads
- Replace new BuilderFieldDto() test setup with streamed builder usage;
  extend ProcessorDtoBuildersTest to cover the new collection methods
… usage sites

Replace new XxxDto() + setter call sequences in processor main code and
test-input samples with the streamed builder API, using nested
element-builder consumers for parameters, annotations, methods and
nested types (BuilderDefinitionCreator, BuilderToGenerationTypeMapper,
builder/field enhancers and generators, JacksonModuleGenerator,
MethodGeneratorUtil, CustomizingDocumentationTest). Loop-mutated DTOs
(MethodCodeDto/JavadocCodeBlockDto) stay as-is.
…ber helpers

- move the 8 classes copied from simple-builders-core from the mirrored
  {builders,interfaces,util} subpackages to org.javahelpers.codegen.builders
- add2Imports/add2FieldTypeImports/add2CodeBlockImports(Class|TypeName)
  create RegularImport entries without manual ImportStatement wiring
- add2Members(key, value) on AnnotationDtoBuilder for single map entries
- tests use the add2X element adders; revert stray pom whitespace change
}

@Override
public void append(StringBuffer buffer, String fieldName, Object value, Boolean fullDetail) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This has to be an exact @Override: ReflectionToStringBuilder dispatches to append(StringBuffer, String, Object, Boolean) and the style intercepts that call to unwrap TrackedValue fields (only set values are rendered). Renaming would silently break the mechanism — callers reach it through the supertype signature by design. Suppressed inline with codeql[java/confusing-method-signature] plus a justification comment.

…dcard handling, suppress CodeQL override warning

- ProcessorDtoBuildersTest: add MIT license header (fixes license:check CI failure)
- ImportCollector: revert early-return for TypeNameWildcard; addImport already
  unwraps bounds since java-helpers#436, so the block was a no-op
- BuilderToStringStyle: justify and suppress java/confusing-method-signature;
  the exact @OverRide is required to unwrap TrackedValue fields

This branch has not been deployed

No deployments
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