Home > Back-end >  If i need to use same variables in several methods - should i define them on a class level or locall
If i need to use same variables in several methods - should i define them on a class level or locall

Time:10-14

I do not need to change the values of str1 and str2, so they are final. These variables are not a part of an object, they just need for some check inside the method1() and method2().

So not to repeat the code - is it ok to define them on class level or should i make them local?

class level:

private final String str1 = "";
private final String str2 = "";

private void method1() {
    // some stuff with 'str1' and 'str2'
}
private void method2() {
    // some stuff with 'str1' and 'str2'
}

or local:

private void method1() {
    final String str1 = "";
    final String str2 = "";
    // some stuff with 'str1' and 'str2'
}
private void method2() {
    final String str1 = "";
    final String str2 = "";
    // some stuff with 'str1' and 'str2'
}

CodePudding user response:

As you have mentioned that "I do not need to change the values of str1 and str2, so they are final."

It is always a good practice to declare them as static final (and as this is String I would rather use word "Java Constant" here).

And as it is going to be constant correct way to declare that would be all upper case:

private final String STR_1 = "xxxx";
private final String STR_2 = "yyyy";

And avoid using STR kind of generic variable (constant) name, rather prefer giving some logical names to these constants as per your context. So that they make much more sense and increase code readability.

CodePudding user response:

If they are real constants (always the same value) then you can do:

private static final String MY_CONSTANT = "give me teh codez";

If they are initialized at object creation you can do:

public class MyClass {

    private final String myField;

    public MyClass(String fieldValue) {
        myField = fieldValue;
    }
}

In both these cases there is really no argument for keeping them as local variables.

However if the values are computed or received after object creation there is a decision to be made.

Some classes (e.g. controllers or services in most web application frameworks) have to be 'stateless' - they cannot store per-request state in their fields. You often see lots of parameters being passed between methods in such classes, which is a code smell. Solution could be to create a separate collaborating class like a Builder/Mapper/Handler/Processor to do a partial task on per-request data. After the task is done, the instance is no longer used. Within this collaborator you can put per-request data in fields and access it from different methods.

In general, methods should not have too many parameters. 1-3 parameters is fine. 4-7 is danger zone. More than 7 is definitely too much.

  •  Tags:  
  • java
  • Related