Skip to content

Commit

Permalink
Merge pull request #26 from Jack-Edwards/try-from
Browse files Browse the repository at this point in the history
Implement validation without throwing exceptions
  • Loading branch information
mcintyre321 authored Mar 4, 2022
2 parents c57be26 + 589137d commit 84e9e84
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
34 changes: 34 additions & 0 deletions ValueOf.Tests/TryValidate.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using NUnit.Framework;

namespace ValueOf.Tests
{
public class TryValidateClientRef : ValueOf<string, TryValidateClientRef>
{
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);
}
}
}
17 changes: 17 additions & 0 deletions ValueOf/ValueOf.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ protected virtual void Validate()
{
}

protected virtual bool TryValidate()
{
return true;
}

static ValueOf()
{
ConstructorInfo ctor = typeof(TThis)
Expand All @@ -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<TValue, TThis> other)
{
return EqualityComparer<TValue>.Default.Equals(Value, other.Value);
Expand Down

0 comments on commit 84e9e84

Please sign in to comment.