Best Practice to set a variable value(Hard Code) i

2019-06-13 18:21发布

i am trying to set a string value(for variable env) as follows for all the objects:-

public class example{
private String env;
public String getEnv() {
        return env;
    }
public void setEnv(String env) {
        this.env = "IN";
    }
}

is it the right way to Hard code the variable value or any better way to do it.

Thanks.

5条回答
相关推荐>>
2楼-- · 2019-06-13 19:02

Create a constants file which contains all the Strings necessary. Make the String public static and final. Then use it in your code

Example: this.env =  ConstantsFile.IN; 

// tomorrow you can change its value to 
"pinnnn" only in the Constants file and not worry 
about changing every other filed that uses "IN" (now "pinnnn" :) ).

This keeps your code clean and reduces dependency.

查看更多
ら.Afraid
3楼-- · 2019-06-13 19:07

First of all, do not start class names with small letters, because it's against convention.

You can just set the value in constructor, like that:

public class Example {
    private final String env = "IN";
    public String getEnv() {
        return env;
    }
}

Have in mind that this way you will not be able to change this value anymore. For that you would need to define a proper setter:

public void setEnv(final String env) {
    this.env = env;
}

and remove the "final" of field "env".

查看更多
成全新的幸福
4楼-- · 2019-06-13 19:10

Don't hard coded, just keep the method taking any value, the specify the value you want out side the method.

public void setEnv(String env) {
    this.env = env;
}

Then:

String currValue = "IN";
obj.setEnv(currValue);

But if you don't want to change the value, then don't create a setter method at all.

private final String env = "IN";

and then just read the value.

public String getEnv() {
   return env;
}
查看更多
甜甜的少女心
5楼-- · 2019-06-13 19:14

You can assign it directly in the attribute definition:

public class Example{
    private String env = "IN";
    public String getEnv() {
        return env;
    } 

    public void setEnv(String env) {
        this.env = env;
    }
}
查看更多
太酷不给撩
6楼-- · 2019-06-13 19:18

If the variable is always going to have the same value, declaring it as final is the best practice.

private final String env = "IN";

If the variable is not dependent on objects, declare it as static as well

private final String env = "IN";

查看更多
登录 后发表回答