简体   繁体   中英

Best way to access hard Coded Map or array etc. in C# and java (languages that have GC )

In programming languages that have garbage collector, what is the best way to access hard coded variables and objects. I have 2 options:

OPTION 1:

class Hello {
    void retrieveData() {
       Map map = App.staticMap;
  }
}

public class App {
  public static Map map = new Map<>() {
      "a", "b",
      "b", "d",
   //hundreds of lines      
 }
}

OPTION 2:

class Hello {

  void retrieveData() {
    //let assume App instance is declared when program is started.
     Map map = App.getInstance().dataMap;
  }
}

public class App {
 private static App instance; 
 Map dataMap = new Map() <> {
   //hundreds of lines
 }

 public static App getInstance() {
    return instance;
 }
}

I couldnt find best way because of garbage collector. When i call static variable, maybe garbage collector collected it before calling. I guess the same thing is valid for instance object. Which one is the best way in JAVA and C# ? or are there options?

The garbage collector will not collect static references - the rule is that an object becomes eligible for garbage collection when it is not reachable by any live thread. Static objects are always reachable, so they should never be collected: link

For your examples, here are some good practice suggestions:

-Don't access fields directly, it's better to provide a getter. This gives you flexibility to change your implementation later.

-Don't use instance methods to access static fields. This makes for confusing, hard to read code.

-Try to avoid hard-coding data - could you use a properties file to store this map information? Then it would be configurable if you need to change it later.

-Maybe overkill for your needs here, but it might be worth looking into the enum singleton pattern rather than just a static field.

If you really want to hard-code it, my preferred implementation would be

public class App {
  private static Map map = new Map<>() {
      "a", "b",
      "b", "d",
   //hundreds of lines      
 }

 public Map getMap(){
   return map;
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM