Last active
June 26, 2023 20:02
-
-
Save solrevdev/76e1a33e01f427978d019f08f2bcec01 to your computer and use it in GitHub Desktop.
A Money value object class/record and a generic result class/record wrapper to return it
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public record Money | |
| { | |
| private static readonly IReadOnlyCollection<string> SupportedCurrencies = new[] { "GBP", "EUR" }; | |
| public decimal Amount { get; } | |
| public string Currency { get; } | |
| private Money(decimal amount, string currency) | |
| { | |
| Amount = amount; | |
| Currency = currency; | |
| } | |
| public static Result<Money> Create(decimal amount, string currency) | |
| { | |
| if (string.IsNullOrWhiteSpace(currency)) | |
| { | |
| return Result<Money>.Failure($"{nameof(currency)} cannot be null or whitespace."); | |
| } | |
| if (!SupportedCurrencies.Contains(currency.ToUpperInvariant())) | |
| { | |
| return Result<Money>.Failure($"'{currency}' is not supported."); | |
| } | |
| return Result<Money>.Success(new(amount, currency)); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public record Result<T> | |
| { | |
| public bool IsSuccess { get; private init; } | |
| public T? Value { get; private init; } | |
| public string? ErrorMessage { get; private init; } | |
| private Result() { } | |
| public static Result<T> Success(T value) => new() { IsSuccess = true, Value = value }; | |
| public static Result<T> Failure(string errorMessage) => new() | |
| { | |
| IsSuccess = false, | |
| ErrorMessage = errorMessage | |
| }; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment