Skip to content

Thoughts on Default Values

Laird Nelson edited this page Nov 6, 2021 · 1 revision

One of the mistakes configuration system authors always seem to make is to try to allow some kind of simple way to specify a default value for a property. There are so many things wrong with this I don't even know where to start.

When you begin to see that an application developer wants an object to be delivered, then when a deliverer can't be found, what might need to be defaulted is the deliverer, not the value it delivers.

So you might at heart want a Car, but you can't easily provide some kind of default representation of a Car in an annotation-suitable String for example. Really what you want to specify is a Supplier<Car> as the default deliverer.

Then there's the case where you get a provider of Cars, so you found one, i.e. the configuration system is working, and from time to time it returns null from its get() method. Maybe this is legal! Should you use "default value" machinery to trump this case? Who knows? Only the application developer knows.

It would be nice to be able to extend Optional, but we can't.

So maybe we can make ConfiguredSupplier implement a new interface (which really should be in the JDK) named something like OptionalSupplier which has all the various orElse() methods that exist on Optional but is also a Supplier (so get() works). Then the user can do:

final Car car = configuredSupplier.of("sports", Car.class).orElseGet(() -> minivan);