diff --git a/CutList/Common/Result.cs b/CutList/Common/Result.cs new file mode 100644 index 0000000..628bf7e --- /dev/null +++ b/CutList/Common/Result.cs @@ -0,0 +1,96 @@ +using System; + +namespace CutList.Common +{ + /// + /// Represents the result of an operation that can either succeed with a value or fail with an error. + /// Implements the Result pattern for standardized error handling. + /// + /// The type of the success value + public class Result + { + private Result(T value, bool isSuccess, string error) + { + Value = value; + IsSuccess = isSuccess; + Error = error; + } + + public T Value { get; } + public bool IsSuccess { get; } + public bool IsFailure => !IsSuccess; + public string Error { get; } + + /// + /// Creates a successful result with a value. + /// + public static Result Success(T value) + { + return new Result(value, true, null); + } + + /// + /// Creates a failed result with an error message. + /// + public static Result Failure(string error) + { + if (string.IsNullOrWhiteSpace(error)) + throw new ArgumentException("Error message cannot be empty", nameof(error)); + + return new Result(default(T), false, error); + } + + /// + /// Maps the success value to a new result type. + /// + public Result Map(Func mapper) + { + if (IsFailure) + return Result.Failure(Error); + + try + { + return Result.Success(mapper(Value)); + } + catch (Exception ex) + { + return Result.Failure(ex.Message); + } + } + } + + /// + /// Represents the result of an operation that can succeed or fail without a return value. + /// + public class Result + { + protected Result(bool isSuccess, string error) + { + IsSuccess = isSuccess; + Error = error; + } + + public bool IsSuccess { get; } + public bool IsFailure => !IsSuccess; + public string Error { get; } + + /// + /// Creates a successful result. + /// + public static Result Success() + { + return new Result(true, null); + } + + /// + /// Creates a failed result with an error message. + /// + public static Result Failure(string error) + { + if (string.IsNullOrWhiteSpace(error)) + throw new ArgumentException("Error message cannot be empty", nameof(error)); + + return new Result(false, error); + } + } +}