Skip to content

Instantly share code, notes, and snippets.

@golavr
Created December 8, 2018 21:52
Show Gist options
  • Save golavr/5f0f55da6a3b60dea1e365d3420bac9b to your computer and use it in GitHub Desktop.
Save golavr/5f0f55da6a3b60dea1e365d3420bac9b to your computer and use it in GitHub Desktop.
OnFailureCompensate - get back to success track the functional way
using System;
using CSharpFunctionalExtensions;
namespace OnFailureCompensate
{
class Program
{
static void Main(string[] args)
{
FunctionalWithoutCompensate(1);
FunctionalWithoutCompensate(0);
FunctionalWithCompensate(1);
FunctionalWithCompensate(0);
}
static void FunctionalWithoutCompensate(int simValue)
{
Result.Ok()
.OnSuccess(() => ReadValue(simValue))
.Ensure(value => value == 1, "value needs to be 1")
.OnBoth(result =>
{
if (!result.IsFailure) return result;
Log(result.Error);
return FixTheResult();
})
.OnBoth(result => PrintResult(result));
}
static void FunctionalWithCompensate(int simValue)
{
Result.Ok()
.OnSuccess(() => ReadValue(simValue))
.Ensure(value => value == 1, "value needs to be 1")
.OnFailure(error => Log(error))
.OnFailureCompensate(() => FixTheResult())
.OnBoth(result => PrintResult(result));
}
private static Result PrintResult(Result<int> result)
{
Console.WriteLine(result.Value);
return result;
}
private static Result<int> FixTheResult()
{
return Result.Ok(1);
}
static Result<int> ReadValue(int simValue)
{
return Result.Ok(simValue);
}
static Result Log(string message)
{
return Result.Ok();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment