Skip to content

[java] New rule: AvoidVarForShortType - #6904

Closed
AB-xdev wants to merge 12 commits into
pmd:mainfrom
AB-xdev:AvoidVarForShortType
Closed

AB-xdev wants to merge 12 commits into
pmd:mainfrom
AB-xdev:AvoidVarForShortType

Conversation

@AB-xdev

@AB-xdev AB-xdev commented Jul 23, 2026 •

Copy link
Copy Markdown

Describe the PR

The PR introduces a new rule: AvoidVarForShortType (see docs in PR and issue below for details)

Other noteworthy changes in this PR:

Related issues

Ready?

  • Added unit tests for fixed bug/feature
  • Passing all unit tests
  • Complete build ./mvnw clean verify passes (checked automatically by github actions)
  • Added (in-code) documentation (if needed)
    • Not needed as code is effectively self explaining

@UncleOwen

Copy link
Copy Markdown
Member

There's already an intellij code style config at https://github.com/pmd/build-tools/blob/main/intellij-idea/PMD-code-style.xml

@AB-xdev

AB-xdev commented Jul 23, 2026

Copy link
Copy Markdown
Author

There's already an intellij code style config at https://github.com/pmd/build-tools/blob/main/intellij-idea/PMD-code-style.xml

Thank you for the hint. I updated the integrated file accordingly.

@UncleOwen

Copy link
Copy Markdown
Member

Please don't include the intellij config at all. We don't want to have to maintain two copies of it.

@AB-xdev

AB-xdev commented Jul 24, 2026

Copy link
Copy Markdown
Author

Please don't include the intellij config at all. We don't want to have to maintain two copies of it.

Currently everybody has to maintain the codestyle because you manually have to get, update and apply it to your projects.

How about then just keeping the one that is automatically used to configure the IDE when opening the project and not the one that is you get by:

Anyway I will rollback these changes for now on this PR.

@AB-xdev
AB-xdev marked this pull request as draft July 24, 2026 06:46
@AB-xdev
AB-xdev force-pushed the AvoidVarForShortType branch from 6b3b386 to c23cb51 Compare July 24, 2026 06:49
@AB-xdev
AB-xdev marked this pull request as ready for review July 24, 2026 06:52
@UncleOwen

Copy link
Copy Markdown
Member

Hey, thanks for this PR and sorry for the late feedback! Could you please:

  • Move TypePrettyPrint/TypePrettyPrinter/PrettyPrintVisitor back to where they were. Splitting them up might make sense, but doing so in this PR makes reviewing your other changes more difficult than necessary.
  • Move your tests into a file AvoidVarForShortType.xml. Have a look at the existing rules to see what it looks like.

@AB-xdev
AB-xdev marked this pull request as draft August 7, 2026 09:26
@AB-xdev
AB-xdev force-pushed the AvoidVarForShortType branch 3 times, most recently from a433c43 to 385df32 Compare August 7, 2026 09:52
@AB-xdev
AB-xdev force-pushed the AvoidVarForShortType branch from 58adc96 to 9ce19f2 Compare August 7, 2026 10:24
@AB-xdev
AB-xdev marked this pull request as ready for review August 7, 2026 10:24
@AB-xdev

AB-xdev commented Aug 7, 2026

Copy link
Copy Markdown
Author

@UncleOwen
I addressed your comments and rebased the branch. Happy reviewing :)

@UncleOwen UncleOwen left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Partial review. I will continue, once these concerns are addressed.

I'm also worried about this comment at the top of TypePrettyPrint.java:

/**
 * Pretty-printing methods to display types. The current API is only
 * offered for debugging, not for displaying types to users.
 */

@oowekyala Do you remember, why this is there?

try {
variableTypeMirror.acceptVisitor(Visitor.INSTANCE, state);
} catch (OverLengthLimitException ignored) {
// Quick exit/abort to not compute full string length

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Have you measured this? I really don't like using exceptions like this. Computing the total length and checking it here would make the code much simpler, IMHO.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

When this rule is active likely all var statements in the scanned code will be greater than the limit or the user would have fixed them otherwise.
Computing/Resolving/Visiting any further elements once we are over the limit makes no sense and would just be a waste of resources and time.

I'm not sure if there is a better way (can the visiting somehow be canceled maybe?) but the exception based approach looked like a straightforward one.

And no I did no measurement as I deemed it not necessary as described by my above theoretical assumptions.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Creating an exception isn't cheap either, filling in the stack trace is an expansive native call.

Please start from the most simple, most readable code (that is in this case: just build the full type name) and show that we actually need performance optimizations. Otherwise I'll think this is all premature optimization.

final int limitLength;
final List<String> currentClassDeclarationCanonicalPrefixes;

int currentLength;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Do we need this variable? Isn't this just super.sb.length()?

@AB-xdev AB-xdev Aug 12, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Yes, because the check for this variable is executed before the string builder is append.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

See my note about premature optimization.

Comment on lines +141 to +156
if (!s.currentClassDeclarationCanonicalPrefixes.isEmpty()) {
// last -> top-most
final String topMostCurrentClassDeclarationBinaryName =
s.currentClassDeclarationCanonicalPrefixes.get(
s.currentClassDeclarationCanonicalPrefixes.size() - 1);
if (canonicalName.startsWith(topMostCurrentClassDeclarationBinaryName)) {
final Optional<String> optMostMatchedCanonicalClassPrefix =
s.currentClassDeclarationCanonicalPrefixes.stream()
.filter(canonicalName::startsWith)
.findFirst();
if (optMostMatchedCanonicalClassPrefix.isPresent()) {
s.append(canonicalName.substring(optMostMatchedCanonicalClassPrefix.get().length()));
return;
}
}
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I don't understand what you're doing here. Is this for nested classes? Can't you get whatever you need here from enclosing.getSymbol()?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Correct.

This code is for resolving the names of subclasses / nested classes. (e.g. simplifying Foo.Bar to Bar when inside Foo)

However enclosing is not usable because it's null here.

If there is a better way, feel free to leave a comment :)

@UncleOwen UncleOwen Aug 12, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Ah, so you're calculating the relative type name, so to speak.

enclosing is null, because none of your test cases have any nested classes. At least that's my guess.

</example>
</rule>

<rule name="AvoidVarForShortType"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the PR!

Just one note on the name of the new rule. Using "short" here immediately made me think of the actual short primitive type that Java has. And we once (in PMD 6) had a rule AvoidUsingShortType...

So maybe something like "AvoidVarForSimpleType" might be better?

We use however "short" already for a couple of other rules in the same meaning like here (ShortClassName, ShortMethodName, ShortVariable), in that sense it seems to be consistent with what we have. Maybe the combination "ShortType" is what makes it misleading for me?

Maybe a more different name would be better? Something more neutral, like "VarForSimpleType" maybe? Looking at https://docs.pmd-code.org/latest/pmd_devdocs_major_rule_guidelines.html that name would better comply with "Do use rule names that name the underlying problem that violations exhibit" - the word "avoid" is just the reason, why one wants to have this rule enabled...

@zbynek

zbynek commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

There is another rule for controlling when var is allowed: https://docs.pmd-code.org/latest/pmd_rules_java_codestyle.html#useexplicittypes
Maybe worth deciding if any of the exceptions allowed by that one should be allowed by this one, in case someone has the existing rule configured and wants to allow long names (or maybe turn this new rule into another property of UseExplicitTypes called allowTypesLongerThan?).

@AB-xdev

AB-xdev commented Aug 12, 2026

Copy link
Copy Markdown
Author

Ok so regarding all the comments here:

Thank you for the hint with UseExplicitTypes I didn't know this rule existed yet.
I'm not sure if both rules can be merged reasonably because one is an XPathRule while the other one is based on Java - due to type pretty printing not being doable (as of now) in XPath. Feel free to give some input how I should proceed here.

As for the name if this would be a separate rule: How about something like UseExcplicitTypesForSimpleTypes?

* restored original CaptureMatcher
* refactored `computeCurrentClassDeclarationCanonicalPrefixes` because recursion is not needed
* improved logic for limit
@AB-xdev

AB-xdev commented Aug 12, 2026

Copy link
Copy Markdown
Author

@UncleOwen
I refactored the PR accordingly to your comments :)

@UncleOwen

Copy link
Copy Markdown
Member

Merging the two rules should be straightforward: Convert UseExplicitTypes to a java rule, then add what we have here.

@adangel adangel added the a:new-rule Proposal to add a new built-in rule label Sep 18, 2026
@adangel

adangel commented Sep 18, 2026

Copy link
Copy Markdown
Member

Maybe worth deciding if any of the exceptions allowed by that one should be allowed by this one, in case someone has the existing rule configured and wants to allow long names (or maybe turn this new rule into another property of UseExplicitTypes called allowTypesLongerThan?).

Merging the two rules should be straightforward: Convert UseExplicitTypes to a java rule, then add what we have here.

I've started a prototype for this approach -> #7088

I think, the new feature (allow var when the type name would be longer than ...) nicely fits into the existing rule.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

a:new-rule Proposal to add a new built-in rule

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[java] Enhance UseExplicitTypes to allow verbose long explicit types

4 participants