1
0
mirror of https://github.com/chylex/TweetDuck.git synced 2025-04-22 18:15:47 +02:00

Add a Result class that acts as an Either monad for a value or exception

This commit is contained in:
chylex 2018-04-10 19:45:41 +02:00
parent f3072caea8
commit f99d035621
2 changed files with 37 additions and 0 deletions

36
Data/Result.cs Normal file
View File

@ -0,0 +1,36 @@
using System;
namespace TweetDuck.Data{
sealed class Result<T>{
public bool HasValue => exception == null;
public T Value => HasValue ? value : throw new InvalidOperationException("Requested value from a failed result.");
public Exception Exception => exception ?? throw new InvalidOperationException("Requested exception from a successful result.");
private readonly T value;
private readonly Exception exception;
public Result(T value){
this.value = value;
this.exception = null;
}
public Result(Exception exception){
this.value = default(T);
this.exception = exception ?? throw new ArgumentNullException(nameof(exception));
}
public void Handle(Action<T> onSuccess, Action<Exception> onException){
if (HasValue){
onSuccess(value);
}
else{
onException(exception);
}
}
public Result<R> Select<R>(Func<T, R> map){
return HasValue ? new Result<R>(map(value)) : new Result<R>(exception);
}
}
}

View File

@ -259,6 +259,7 @@
</Compile>
<Compile Include="Core\Notification\Screenshot\TweetScreenshotManager.cs" />
<Compile Include="Data\ResourceLink.cs" />
<Compile Include="Data\Result.cs" />
<Compile Include="Data\Serialization\FileSerializer.cs" />
<Compile Include="Data\InjectedHTML.cs" />
<Compile Include="Data\Serialization\ITypeConverter.cs" />