2

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.

  • Why don't you write a kind of key-builder-factory, which build your key depending on your 3 parameters? – Thilo Schwarz Feb 10 '22 at 16:41
  • I don't want to use factory because I'm eventually returning a hard-coded string stored in application.properties. For example, I have this value stored in application.properties "folder.canada.6m.ind= 150992762918" Lets say I receive parameters from client (canada, 6m, ind) then I'm directly able to fetch this value using "get(folder.canada.6m.ind)" without using a lot of if-elses. Please note that "canada, 6m, ind" values can change and they will have different corresponding values. – Karanbir Singh Mann Feb 10 '22 at 17:25
  • You don't need any if-else-statment to do this, just: ```String key = String.format("folder.%s.%s.%s", country, month, category)``` – Thilo Schwarz Feb 10 '22 at 18:00
  • This will get me my variable name stored in a string, yes. But now i have to fetch the value of this variable as well. – Karanbir Singh Mann Feb 10 '22 at 21:49

1 Answers1

1

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.

Thilo Schwarz
  • 640
  • 5
  • 24