semver4j
semver4j copied to clipboard
Null safe coercion
So coerce and parse both return null if they can't... determine something sensible. This of course can lead to null pointer errors down the road. I think it'd be nice to have something that either eagerly throws, and/or something that chains into the builder where I could conditionally check if they're missing.
Some ideas
var defaultV = Semver.coerceOr(string, Semver.of(0,0,0))); // provide a default
var builder = Semver.coerceToBuilder(string); // add a version that returns a builder
if (!builder.hasMajor()) builder.major(0);
Semver.coerceOrThrow(string); // throw an IllegalArgumentException
Semver.coerce(string).orElseThrow() // change coerce to return an Optional
the alternatives feels weird
var semver = Semver.coerce(string) != null ? Semver.coerce(string) : Semver.of(0,0,0);
var semver = Objects.requireNonNull(Semver.coerce(string);
Honestly I think I'd prefer a version that didn't throw. The default feels like the safest thing at this point as it won't require breaking the current API. The Optional might be the nicest because it's terse and lets the consumer decide what to do, but as proposed breaks backwards compatibility. I suppose something like coerceOptional could work in lieu of a major version.
Right now, this could be handled as you mentioned - by using Optional:
Semver semver1 = Optional.ofNullable(Semver.coerce("boom")).orElse(new Semver("0.0.0"));
Semver semver2 = Optional.ofNullable(Semver.coerce("boom")).orElseThrow();
I think it's a fair enough mechanism. So right now I'm against adding this.
There is also Objects.requireNonNullElse:
var semver = Objects.requireNonNullElse(Semver.coerce(string), Semver.of(0, 0, 0));
var semver = Objects.requireNonNull(Semver.coerce(string);