Skip to content

Commit 486a4f3

Browse files
Add methods to Configuration to more easily express the default-value and throw-if-absent modes
1 parent 217fced commit 486a4f3

3 files changed

Lines changed: 34 additions & 0 deletions

File tree

src/main/java/co/unruly/config/Configuration.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,14 @@ public Optional<String> get(String s) {
2525
return Optional.ofNullable(func.get(s));
2626
}
2727

28+
public String get(String s, String defaultValue) {
29+
return get(s).orElse(defaultValue);
30+
}
31+
32+
public String require(String s) {
33+
return get(s).orElseThrow(() -> new ConfigurationMissing(s));
34+
}
35+
2836
public Configuration or(ConfigurationSource next) {
2937
return new Configuration(this.func.or(next));
3038
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package co.unruly.config;
2+
3+
public class ConfigurationMissing extends RuntimeException {
4+
5+
public ConfigurationMissing(String property) {
6+
super(property + " not found in configuration");
7+
}
8+
}

src/test/java/co/unruly/config/ConfigurationTest.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,24 @@ public void shouldReturnEmptyOptionalIfValueNotFound() {
2727
assertThat(config.get("some-variable"), is(empty()));
2828
}
2929

30+
@Test
31+
public void shouldReturnDefaultValueIfProvidedAndValueNotFound() {
32+
Map<String, String> input = Collections.emptyMap();
33+
34+
Configuration config = Configuration.from(map(input));
35+
36+
assertThat(config.get("some-variable", "default-value"), is("default-value"));
37+
}
38+
39+
@Test(expected = ConfigurationMissing.class)
40+
public void shouldThrowIfRequiredValueNotFound() {
41+
Map<String, String> input = Collections.emptyMap();
42+
43+
Configuration config = Configuration.from(map(input));
44+
45+
config.require("some-variable");
46+
}
47+
3048
@Test
3149
public void shouldReturnOptionalIfValueIsPresent() {
3250
Map<String, String> input = new HashMap<>();

0 commit comments

Comments
 (0)