Search code examples
javastaticsettingsstatic-methodsapplication-settings

Is it ok to manipulate static attributes on runtime?


I am providing Settings of my JAVA project in a Prefs.java class with static attributes and static methods. But the token for OAuth2 needs to be assigned on runtime. Is this a good way to go... ?

public class Prefs {


  //known before runtime
  public static final String SERVER_BASE_URL ="http://api.mycompany.com/";

  //needs to be set on startup through the setter method
  private static String token;


  public static String getToken() {
    return token;
  }

  public static void setToken( String token ) {
    Prefs.token = token;
  }

  public static String getXyEndpointUrl() {
    return SERVER_BASE_URL + "/xy";

  }
}

Solution

  • I would advice against such design. This type of static variables no better than global variables. This page gives a few reasons why you should avoid them. Here are a few of them.

    • Non-locality
    • No Access Control or Constraint Checking
    • Implicit coupling
    • Concurrency issues
    • Testing and Confinement

    But the token for OAuth2 needs to be assigned on runtime. Is this a good way to go... ?

    Here it really seems to me like you would want to pass such token to the constructor of the Prefs object.