Skip to content

Feature Request: Recipe to Extract Magic Numbers to Type-and-Value-Named Constants per Class #768

@boraciner

Description

@boraciner

Hi team,
In order to fix "Magic numbers should not be usedjava:S109" problems in my code.
I’d love to see a new recipe that detects all magic numbers scattered throughout a codebase and, for each unique magic number in a class, introduces a constant at the top of that class named using the pattern TYPE_VALUE (e.g., INT10 for 10, DOUBLE23_5 for 23.5). The recipe would then replace all usages of that magic number within the class with the generated constant.

Desired behavior:

For every integer/double/float/etc. literal not already assigned to a constant, automatically declare a private static final constant at the top of the class, following the TYPE_VALUE (or similar) naming convention.
Replace each magic number occurrence in the class with the appropriate constant.
Type and value should be part of the constant name (e.g., INT42, DOUBLE3_14), to avoid collisions and increase readability.
Support commonly used primitive types (int, double, float, long, etc.).
Motivation:

Prevents code duplication and improves maintainability.
Enables fully automated removal of magic numbers, even in large legacy projects.
This would be a huge help for modernizing legacy codebases with large numbers of magic numbers across many classes.

Thank you very much for considering this enhancement!

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requestquestionFurther information is requestedrecipe

    Type

    No type

    Projects

    Status

    Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions