From 69d582c0edb0b52df21266c8128a1f63ac62f8f3 Mon Sep 17 00:00:00 2001 From: Kyle Ratti Date: Tue, 30 Apr 2024 13:36:31 -0400 Subject: [PATCH] BREAKING CHANGE: feat: use 'is empty' instead of 'has value' --- Base.Tests/Structures/MaybeExtensionTests.cs | 2 +- Base/Structures/Maybe.cs | 22 +++++++++++++------- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/Base.Tests/Structures/MaybeExtensionTests.cs b/Base.Tests/Structures/MaybeExtensionTests.cs index a1cdf54..cf817d6 100644 --- a/Base.Tests/Structures/MaybeExtensionTests.cs +++ b/Base.Tests/Structures/MaybeExtensionTests.cs @@ -26,7 +26,7 @@ public class MaybeExtensionTests public void MaybeNullableTests() { Assert.IsNull(Maybe.Empty().ToNullable()); - Assert.IsNull(Maybe.Create(0, hasValue: _ => false).ToNullable()); + Assert.IsNull(Maybe.Create(0, evalIsEmpty: () => true).ToNullable()); } [Test] diff --git a/Base/Structures/Maybe.cs b/Base/Structures/Maybe.cs index 315c553..13c88c7 100644 --- a/Base/Structures/Maybe.cs +++ b/Base/Structures/Maybe.cs @@ -4,20 +4,25 @@ using System; public static class Maybe { - public static Maybe Create(T value) => new(value, hasValue: true); - public static Maybe Create(T value, Func hasValue) => new(value, hasValue: hasValue(value)); - public static Maybe Empty() => new(val: default!, hasValue: false); + public static Maybe Create(T value) => new(value); + + public static Maybe Create(T value, Func evalIsEmpty) => + evalIsEmpty() + ? Empty() + : new Maybe(value); + + public static Maybe Empty() => new(); } public readonly record struct Maybe { private readonly T _value; - public readonly bool HasValue; + public bool HasValue { get; } - internal Maybe(T val, bool hasValue) + internal Maybe(T val) : this() { _value = val; - HasValue = hasValue; + HasValue = true; } public T Value @@ -77,7 +82,10 @@ public readonly record struct Maybe ? default : (TOutput)Convert.ChangeType(Value, t); - return Maybe.Create(output, hasValue: _ => output != null)!; + if (output == null) + return Maybe.Empty(); + + return Maybe.Create(output); } catch (InvalidCastException) {