ZiggyCreatures / FusionCache

FusionCache is an easy to use, fast and robust hybrid cache with advanced resiliency features.
MIT License
1.91k stars 97 forks source link

Using `MaybeValue<T>` also as the return value of TryGet[Async] method #10

Closed jodydonetti closed 3 years ago

jodydonetti commented 3 years ago

I'm thinking about using the new type MaybeValue<T> - introduced for the new failSafeDefaultValue in the GetOrSet method - also as the return value of the TryGetResult<T> method.

The basic rationale behind this is unification of the "maybe a value, maybe not" concept.

The main difference from now would be that TryGetResult<T> implicitly converts to a bool (the idea was to use that in an if statement) whereas MaybeValue<T> implicitly converts to/from a T value, much like a Nullable<T>. But, just like a Nullable<T>, it does have an HasValue property for easy checks, so it should not be that problematic.

In practice, before we should have done one of these:

// ASSIGNMENT + IMPLICIT CONVERSION TO bool, KINDA WEIRD
TryGetResult<int> foo;
if (foo = cache.TryGet<int>("foo"))
{
  var value = foo.Value;
}

// ASSIGNMENT DONE BEFORE
var foo = cache.TryGet<int>("foo");
if (foo)
{
  var value = foo.Value;
}

whereas now we can do one of these:

var foo = cache.TryGet<int>("foo");
if (foo.HasValue) // EXPLICIT .HasValue CHECK
{
  // EXPLICIT .Value USAGE
  var value = foo.Value;
  // OR IMPLICIT CONVERSION, LIKE WITH A Nullable<T>
  var value = foo;
}

// OR .GetValueOrDefault(123) USAGE, LIKE A Nullable<T>
var foo = cache.TryGet<int>("foo");
var value = foo.GetValueOrDefault(123);

Even though FusionCache is still in the 0.X version phase (so can have breaking changes), just in case of existing usage of the TryGet[Async] method in someone else's code I can easily add the old Success prop marked as Obsolete with an explanation on how to use the new thing. Maybe some pieces of code with a direct check in an if statement would stop compiling, but that would be resolved by simply adding .HasValue.

Opinions?

jodydonetti commented 3 years ago

Created a branch for it

https://github.com/jodydonetti/ZiggyCreatures.FusionCache/tree/feature_maybe_everywhere

clxx commented 3 years ago

This looks good and consistent for me!

jodydonetti commented 3 years ago

I've release v0.1.3 containing this change, too 🎉