From 589137dff39b052acb4576a7bef07ab4fac43da0 Mon Sep 17 00:00:00 2001 From: Jack-Edwards Date: Thu, 3 Mar 2022 17:22:13 -0600 Subject: [PATCH] Implement validation without throwing exceptions --- ValueOf.Tests/TryValidate.cs | 34 ++++++++++++++++++++++++++++++++++ ValueOf/ValueOf.cs | 17 +++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 ValueOf.Tests/TryValidate.cs diff --git a/ValueOf.Tests/TryValidate.cs b/ValueOf.Tests/TryValidate.cs new file mode 100644 index 0000000..7b9ef6d --- /dev/null +++ b/ValueOf.Tests/TryValidate.cs @@ -0,0 +1,34 @@ +using NUnit.Framework; + +namespace ValueOf.Tests +{ + public class TryValidateClientRef : ValueOf + { + protected override bool TryValidate() + { + return !string.IsNullOrWhiteSpace(Value); + } + } + + public class TryValidation + { + [Test] + public void TryValidateReturnsFalse() + { + bool isValid = TryValidateClientRef.TryFrom("", out TryValidateClientRef valueObject); + + Assert.IsFalse(isValid); + Assert.IsNull(valueObject); + } + + [Test] + public void TryValidateReturnsTrue() + { + bool isValid = TryValidateClientRef.TryFrom("something", out TryValidateClientRef valueObject); + + Assert.IsTrue(isValid); + Assert.IsNotNull(valueObject); + Assert.AreEqual("something", valueObject.Value); + } + } +} diff --git a/ValueOf/ValueOf.cs b/ValueOf/ValueOf.cs index b707102..e6e5666 100644 --- a/ValueOf/ValueOf.cs +++ b/ValueOf/ValueOf.cs @@ -20,6 +20,11 @@ protected virtual void Validate() { } + protected virtual bool TryValidate() + { + return true; + } + static ValueOf() { ConstructorInfo ctor = typeof(TThis) @@ -45,6 +50,18 @@ public static TThis From(TValue item) return x; } + public static bool TryFrom(TValue item, out TThis thisValue) + { + TThis x = Factory(); + x.Value = item; + + thisValue = x.TryValidate() + ? x + : null; + + return thisValue != null; + } + protected virtual bool Equals(ValueOf other) { return EqualityComparer.Default.Equals(Value, other.Value);