Get a hard-coded value using combination of multiple keys

Viewed 134

I've to store hard-coded value in my environment files like this:

  1. folder.canada.6m.ind=150992762918
  2. folder.canada.9m.group=150992760518
  3. folder.usa.1m.ind=150992762995

There are 3 parameters (String country, String months, String category) which I receive from the end user and I've to pick the corresponding value from env files.

I can do it using brute force like,

if(country.equals(canada) && months.equals(6m) && category.equals(ind)) {
return folder.canada.6m.ind;
}

There are other ways to do it using if-else as well but I have 100's of these values so I don't think the best way to solve this problem is using if-else. What would be the best data structure or method to solve this problem?

I'm using spring-boot in Java.

1 Answers

Spring boot can put your properties into a map. Let's have a look at the following class:

@Configuration
@ConfigurationProperties(prefix = "")
public class FolderConfig {

    private Map<String, String> folder = new HashMap<>();
    
    public void setFolder(Map<String, String> folder) {
        this.folder = folder;
    }
    
    public String getValue(String country, String month, String category) {
        String key = String.format("%s.%s.%s", country, month, category);
        return folder.get(key);
    }
}

The naming of the map is important, because it is used as prefix of your properties keys! This means, the map folder has the following values:

canada.6m.ind=150992762918
canada.9m.group=150992760518
usa.1m.ind=150992762995

You see your keys don't start with folder!

Maybe you should think about throwing an additional exception, if the key doesn't exists.

Related