lightbend / config

configuration library for JVM languages using HOCON files
https://lightbend.github.io/config/
6.12k stars 968 forks source link

introduce method accepting a list of Objects to add a value #785

Open kerbylane opened 1 year ago

kerbylane commented 1 year ago

We are manipulating Configs in a few places in our code and using a good bit of nesting. I find the code to be rather messy because of the need to manipulate String formats to define keys and the final ConfigValueFactory.fromAnyRef() call for the actual value. I am interested in submitting a PR to modify the Config interface based on what I have done to simplify our code. But first I want to ask for feedback on the high level idea. Would this violate some design principal, etc?

To make our code more legible I have created a small helper class that wraps a Config instance. The helper lets the user add values by invoking a method which accepts Object.... The first n-1 elements of the array are converted into a . delimited String which is used as a key. The final element of the array is put through ConfigValueFactory.fromAnyRef().

The result is that lines like this

ConfigFactory.empty()
    .withValue(String.format("%s.%s.%s", k1, k2, k3), ConfigValueFactory.fromAnyRef("value goes here"))

Can be replaced with:

new Helper()
    .withHelperValue(k1, k2, k3, "value goes here")

The benefit is amplified when there are multiple calls to .withValue . Further, I added to the helper class a withFallback wrapper so that it can handle interspersed calls to withHelperValue and withFallback.

A rough interface for the class is:

Helper {
    private Config config;

    Helper configHelperValue(Object ...);

    Helper withFallback(Config);

    Config getConfig();
}

I think that the only thing that would be needed to add this functionality to Config itself would be something like withKeyValue(Object...). The implementation in SimpleConfig is fairly obvious.