Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checkstyle error when not declaring fields as final

I have the following custom exception written in java:

import java.util.List;

public class PolicyException extends RuntimeException {

    private static final long serialVersionUID = -1760901980049241500L;
    private PolicyErrorCode code;
    private List<String> variables;

    public PolicyException(final PolicyErrorCode code, final List<String> variables) {
        this.code = code;
        this.variables = variables;
    }

    public PolicyErrorCode getCode() {
        return code;
    }

    public void setCode(final PolicyErrorCode code) {
        this.code = code;
    }

    public List<String> getVariables() {
        return variables;
    }

    public void setVariables(final List<String> variables) {
        this.variables = variables;
    }
}

I am recieving the following checkstyle errors:

The field 'code' must be declared final.

The field 'variables' must be declared final.

I believe the checkstyle error being thrown is FinalLocalVariableCheck. According to the api:

Ensures that local variables that never get their values changed, must be declared final.

However, clearly there are getters and setters for the variables involved, so they can't be declared final.

These errors do not happen with all my classes, just the custom exceptions, which are serializable due to extending exception.

Am I missing something here? Or is this a checkstyle bug?

I believe this guy had a similar problem, though there seems to be a bit of confusion over the use of static variables in his post.

like image 385
Clarkey Avatar asked Jun 21 '13 14:06

Clarkey


1 Answers

The problem is indeed that you are extending Exception. There is a design rule that exception objects should be immutable. All relevant values should be given in the constructor.

The checkstyle rule seems to be called MutableException and is documented here.

like image 72
André Stannek Avatar answered Sep 27 '22 23:09

André Stannek