Class ParameterAssignmentCheck

  • All Implemented Interfaces:
    Configurable, Contextualizable

    public final class ParameterAssignmentCheck
    extends AbstractCheck

    Disallows assignment of parameters.

    Rationale: Parameter assignment is often considered poor programming practice. Forcing developers to declare parameters as final is often onerous. Having a check ensure that parameters are never assigned would give the best of both worlds.

    To configure the check:

     <module name="ParameterAssignment"/>
     

    Example:

     class MyClass {
       int methodOne(int parameter) {
         if (parameter <= 0 ) {
           throw new IllegalArgumentException("A positive value is expected");
         }
         parameter -= 2;  // violation
         return parameter;
       }
    
       int methodTwo(int parameter) {
         if (parameter <= 0 ) {
           throw new IllegalArgumentException("A positive value is expected");
         }
         int local = parameter;
         local -= 2;  // OK
         return local;
       }
    
       IntPredicate obj = a -> ++a == 12; // violation
       IntBinaryOperator obj2 = (int a, int b) -> {
           a++;     // violation
           b += 12; // violation
           return a + b;
       };
       IntPredicate obj3 = a -> {
           int b = a; // ok
           return ++b == 12;
       };
     }
     

    Parent is com.puppycrawl.tools.checkstyle.TreeWalker

    Violation Message Keys:

    • parameter.assignment
    Since:
    3.2
    • Field Detail

      • MSG_KEY

        public static final java.lang.String MSG_KEY
        A key is pointing to the warning message text in "messages.properties" file.
        See Also:
        Constant Field Values
      • parameterNamesStack

        private final java.util.Deque<java.util.Set<java.lang.String>> parameterNamesStack
        Stack of methods' parameters.
      • parameterNames

        private java.util.Set<java.lang.String> parameterNames
        Current set of parameters.