1

I have a variable that is used in one method. So my linter is telling me to make it local. However I like it being a class level variable in case it any one else modifies the code and needs to use that variable. If it is not class level they might miss it in the method and make a new duplicate variable?

Is my logic reasonable or should I just make it a local variable?

Here is the code :

public class CustomPasswordTransformationMethod extends PasswordTransformationMethod {
    . . . 
    private final char DOT_CHAR = '●';
    . . . 

    public char charAt(int index) {
        if (index < ((length()) - unObfuscated)) return DOT_CHAR;
        return mSource.charAt(index);

    }
}
Dan Anderson
  • 1,062
  • 13
  • 26
  • 4
    It's hard to say without seeing the code, but it's usually best to keep things local and private unless you have a concrete reason not too. – shmosel Mar 25 '19 at 22:42
  • 5
    "in case" When that case arises, move it. Until then, keep it in as tight a scope as possible. – Andy Turner Mar 25 '19 at 22:43
  • 1
    I agree with shmosel, anyway feel free to share with us your code, so maybe we can tell you something more. – tarabor Mar 25 '19 at 22:44

3 Answers3

7

Change to:

private static final char DOT_CHAR = '●';

and now you've created a class constant the right way and the linter will no longer suggest changing it.

Basically the linter is telling you that a private instance variable that is only used in one place is a waste of allocation and should be local to the one place that uses it. By declaring it static, you are telling the compiler you one one copy of a constant for the class which is slightly different. A static constant is allocated once - whereas an instance constant would be created for each instance (and continue to be allocated for the life of each instance), and a local constant would be created for each method call and cleaned up at the end of the call. All of this is in theory - the real implementation of the compiler may optimize things.

Whether to make the constant class-wide or local to a method is a matter of preference for the most part. But to have a non-static final constant only makes sense in very limited cases like if it gets assigned in the constructor and varies from instance to instance.

jt-gilkeson
  • 2,661
  • 1
  • 30
  • 40
1

In your case, as you are defining a constant, I think it's fine to declare it at a class level. Your logic is reasonable.

Further reading that can help: What is the best way to implement constants in Java?

Or

https://google.github.io/styleguide/javaguide.html

tarabor
  • 166
  • 1
  • 7
1

I'd use as a local variable, accessing a local variable is faster than accessing a field.

Leonardo Rivera
  • 174
  • 1
  • 5
  • 2
    Don't optimize until after you measure. I'd wager that it makes no difference that matters. –  Mar 25 '19 at 23:24