Skip to content

fix: warn about uncopyable builder properties - #483

Open
igel-devin-ai wants to merge 9 commits into
java-helpers:mainfrom
igel-devin-ai:devin/1796199106-issue-457-uncopyable-warnings
Open

igel-devin-ai wants to merge 9 commits into
java-helpers:mainfrom
igel-devin-ai:devin/1796199106-issue-457-uncopyable-warnings

Conversation

@igel-devin-ai

Copy link
Copy Markdown
Contributor

Fixes #457.

Summary

  • emit one DTO-level compiler warning listing properties the copy constructor/with() cannot copy
  • report missing getters, getter type mismatches, ignored getters, and unsettable getter-only state
  • document the warning next to generateWithInterface

Verification

  • mvn clean verify

Comment on lines +933 to +946
private static List<ExecutableElement> findGetterCandidates(
TypeElement dtoType, String fieldName, BuilderProcessingContext context) {
if (dtoType == null) {
return List.of();
}
return ElementFilter.methodsIn(context.getAllMembers(dtoType)).stream()
.filter(
candidate -> {
String name = candidate.getSimpleName().toString();
return Strings.CI.equalsAny(name, fieldName, "is" + fieldName, "get" + fieldName)
&& candidate.getParameters().isEmpty();
})
.toList();
}

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.

But we already have a helper for reading getters?

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. I removed the parallel getter-candidate analysis and reuse the existing getter resolution; the warning now derives copyability from the resolved getter metadata.

Comment on lines +933 to +1039
private static List<ExecutableElement> findGetterCandidates(
TypeElement dtoType, String fieldName, BuilderProcessingContext context) {
if (dtoType == null) {
return List.of();
}
return ElementFilter.methodsIn(context.getAllMembers(dtoType)).stream()
.filter(
candidate -> {
String name = candidate.getSimpleName().toString();
return Strings.CI.equalsAny(name, fieldName, "is" + fieldName, "get" + fieldName)
&& candidate.getParameters().isEmpty();
})
.toList();
}

private static String uncopyablePropertyReason(
String fieldName,
TypeMirror fieldTypeMirror,
List<ExecutableElement> typeMatchingGetters,
List<ExecutableElement> getterCandidates) {
if (!typeMatchingGetters.isEmpty()) {
return fieldName + " (getter excluded via @IgnoreInBuilder)";
}
if (getterCandidates.isEmpty()) {
return fieldName + " (no getter found)";
}
return fieldName
+ " (getter returns "
+ getterCandidates.get(0).getReturnType()
+ ", expected "
+ fieldTypeMirror
+ ")";
}

private static void addGetterOnlyUncopyableProperties(
TypeElement annotatedType,
BuilderDefinitionDto builderDto,
BuilderProcessingContext context,
List<String> uncopyableProperties) {
Set<String> builderProperties = new HashSet<>();
for (BuilderFieldDto field : builderDto.getAllFieldsForBuilder()) {
builderProperties.add(field.getOriginalFieldName());
builderProperties.add(field.getFieldNameInBuilder());
}
for (ExecutableElement method : ElementFilter.methodsIn(context.getAllMembers(annotatedType))) {
Optional<String> propertyName = getterOnlyPropertyName(method, context);
if (propertyName.isPresent()
&& !builderProperties.contains(propertyName.get())
&& !hasIgnoredSetter(annotatedType, propertyName.get(), context)
&& uncopyableProperties.stream()
.noneMatch(reason -> reason.startsWith(propertyName.get() + " ("))) {
uncopyableProperties.add(propertyName.get() + " (getter-only state cannot be set)");
}
}
}

private static boolean hasIgnoredSetter(
TypeElement annotatedType, String propertyName, BuilderProcessingContext context) {
String setterName = "set" + StringUtils.capitalize(propertyName);
return ElementFilter.methodsIn(context.getAllMembers(annotatedType)).stream()
.anyMatch(
method ->
Strings.CI.equals(method.getSimpleName().toString(), setterName)
&& method.getParameters().size() == 1
&& !hasNotAnnotation(IgnoreInBuilder.class, method));
}

private static Optional<String> getterOnlyPropertyName(
ExecutableElement method, BuilderProcessingContext context) {
if (!method.getParameters().isEmpty()
|| method.getReturnType().getKind() == javax.lang.model.type.TypeKind.VOID
|| method.getModifiers().contains(Modifier.STATIC)
|| method.getModifiers().contains(Modifier.PRIVATE)
|| !shouldMethodBeIncludedInBuilder(method)
|| !context.isMemberAccessibleFromBuilderPackage(method)
|| method.getEnclosingElement() instanceof TypeElement owner
&& "java.lang.Object".equals(owner.getQualifiedName().toString())) {
return Optional.empty();
}
String name = method.getSimpleName().toString();
String propertyName = null;
if (name.startsWith("get") && name.length() > 3 && Character.isUpperCase(name.charAt(3))) {
propertyName = StringUtils.uncapitalize(name.substring(3));
} else if (name.startsWith("is")
&& name.length() > 2
&& Character.isUpperCase(name.charAt(2))
&& method.getReturnType().getKind() == javax.lang.model.type.TypeKind.BOOLEAN) {
propertyName = StringUtils.uncapitalize(name.substring(2));
}
return Optional.ofNullable(propertyName).filter(SourceVersion::isName);
}

private static void warnAboutUncopyableProperties(
TypeElement annotatedType,
BuilderProcessingContext context,
List<String> uncopyableProperties) {
if (!uncopyableProperties.isEmpty()) {
context.warning(
annotatedType,
"%s: with()/copy constructor cannot copy %d propert%s: %s",
annotatedType.getSimpleName(),
uncopyableProperties.size(),
uncopyableProperties.size() == 1 ? "y" : "ies",
String.join(", ", uncopyableProperties));
}
}

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.

So many changes just for the feature to have a warning instead of silent drop? Could we not just compare the results? Which fields are used for copying and which fields are recognized for builder? The exact reason is not needed, just which fields would not be mapped!

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.

Reworked as suggested. The implementation now compares builder properties with the properties that have copy-readable getters and lists only the unmappable property names; the reason-specific collection and parameter threading are removed.


public int getA() { return a; }
public String getName() { return name; }
@org.javahelpers.simple.builders.core.annotations.IgnoreInBuilder

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.

Add it to
Import and just use the short name

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.

Done. The fixture imports IgnoreInBuilder and uses the short annotation name.

public static void setUtil(int util) {}
public void setRisky(int risk) throws Exception {}
public int returnsInt() { return 42; }
@org.javahelpers.simple.builders.core.annotations.IgnoreInBuilder

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.

Same here

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.

Done here as well. The generated fixture now receives the import through the test utility and uses the short annotation name.

@codecov

codecov Bot commented Dec 5, 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!

@igel-devin-ai

igel-devin-ai commented Dec 6, 2026 •

Copy link
Copy Markdown
Contributor Author

Strict review

changes needed

Reviewed head bc3bd0650c9efcbc7b01340412050257e0c25702 against upstream/main 4b696141058c97b8130c3ce3920a7faeafbb3bbd, including issue #457, the PR body, conversation and inline comments. Names without reason strings are an explicitly accepted simplification in the maintainer's inline review, so the difference from the original issue proposal is not repeated as a defect. The DTO-level consolidated diagnostic and documentation next to generateWithInterface are otherwise appropriate.

  1. major — verified — processor/src/main/java/org/javahelpers/simple/builders/processor/processing/BuilderDefinitionCreator.java:965–969 (comparison at :932–937): boolean getter normalization reports fully copyable state as uncopyable. For a boolean property named isReady, with setIsReady(boolean) and boolean isReady(), existing getter resolution correctly associates the getter with builder property isReady. However, the new getter-only scan unconditionally changes isReady() into property ready. That name is absent from the builder-property set, so it emits ReadyDto: with()/copy constructor cannot copy 1 property: ready. A strict compile-testing probe succeeds with 1 warning, 0 errors, and its generated copy constructor actually contains this.isReady = initialValue(instance.isReady());. The otherwise equivalent setReady/isReady property produces 0 warnings, excluding a general boolean-copy failure. Reuse the resolved getter-to-property association when excluding getters already consumed by a builder property, instead of inventing a second name for them. Add a zero-warning regression for the isX-named property, including its ignored-setter variant. This violates the acceptance criterion that fully copyable DTOs produce no warning and makes warning-as-error builds reject valid DTOs.

  2. nit — verified — processor/src/test/java/org/javahelpers/simple/builders/processor/testing/ProcessorTestUtils.java:178–179,197–198: the rewritten source-fixture helper still concatenates strings. additionalImport is assembled with "import " + importedType.getName() + ";\n", and the source name uses packageName + "." + className. The main fixture body already uses a text block; use text blocks with .formatted(...) for the import and formatted source name as well, following the requested no-concatenation test convention. The name + "!" inside the new warning test's Java text block is code in the fixture, not Java-side construction of a test string, and is not counted as a violation.

Verification

  • Java 17 / Maven 3.9.11: targeted Maven install of codegen-core,codegen-roaster,processor and their reactor dependencies, with formatting disabled, exited 0. Surefire XML totals:
    PR 483: Tests run: 1378, Failures: 0, Errors: 0, Skipped: 0
    
  • External compile-testing probes used -Xlint:rawtypes -Xlint:unchecked -Asimplebuilder.strict=true:
    CASE ReadyDto: SUCCESS warnings=1 errors=0
    CASE NormalReadyDto: SUCCESS warnings=0 errors=0
    CASE ReasonsDto: SUCCESS warnings=1 errors=0
    
    The last fixture combines a missing getter, Optional/String mismatch and ignored getter. It correctly produces one warning naming ignored, missing, optional; omitting individual reasons follows the accepted review decision.
  • Existing new tests cover normal copyability, multiple uncopyable fields, getter-only state and ignored members, but do not cover the boolean naming alias above. Assertions on existing diagnostics do not protect against this false-positive case.
  • git_pr_checks: 6 passed, 0 failed, 0 pending, 0 skipped, including build (17), build (25), CodeQL and codecov/patch.
  • No repository files were edited, no commits/pushes/comments were made, and external probe sources were deleted. No processor-output example changes are expected from a diagnostic-only feature; I did not separately regenerate example modules.

Other-PR integration review

Written by Devin


Recheck at 33756f7b (2026-12-06)

Verdict: minor changes

# Original finding (short) Status Remaining action
1 False warning for copyable isX property fixed —
2 Source-helper string convention partially fixed — nit Concatenation removed; convert import fragment to a text block (ProcessorTestUtils.java:179).

Build: Java 17 module install — BUILD SUCCESS; 1,384 tests, 0 failures/errors; boolean probes have zero warnings; example compile succeeds without tracked drift.


Recheck at 1f3b8635 (2026-12-06)

Verdict: ready

Severity What is missing Where (file:line)
— None. —

…ncopyable scan

- is-getters now resolve both candidate property names (stripped 'ready' and
  prefixed 'isReady'), matching setter-derived properties like setIsReady ->
  isReady; fully copyable boolean state no longer warns
- ignored-setter exclusion checks all candidates, so an explicitly ignored
  isX setter suppresses the warning as intended
- regression tests for both combinations
- nit: text-block/formatted assembly in ProcessorTestUtils fixture helper
@igel-devin-ai

Copy link
Copy Markdown
Contributor Author

Strict-review findings fixed:

  1. Boolean getter normalization — real bug confirmed and fixed: is-getters now resolve both candidate property names (stripped ready and prefixed isReady), matching setter-derived properties like setIsReady → isReady. Fully copyable boolean state no longer produces a false warning; the ignored-setter exclusion checks all candidates. Regression tests for both the plain and the ignored-setter variant added — both fail before, pass after.
  2. Nit — the fixture helper assembles import and source name with .formatted(...) now.

Verified: full processor suite green, 693 tests.

@igel-devin-ai

Copy link
Copy Markdown
Contributor Author

Recheck nit done: the import fragment in ProcessorTestUtils is now assembled as a text block. Tests green, pushed as 1f3b863.

@sonarqubecloud

sonarqubecloud Bot commented Dec 6, 2026

Copy link
Copy Markdown

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.

Warn at compile time when with()/copy constructor cannot copy all properties

2 participants