Skip to content

Instantly share code, notes, and snippets.

@fnbk
Last active September 18, 2022 15:02
Show Gist options
  • Save fnbk/d993d3829827fe10d89ef0de7836deca to your computer and use it in GitHub Desktop.
Save fnbk/d993d3829827fe10d89ef0de7836deca to your computer and use it in GitHub Desktop.
branching: monads
// Create Job
return ValidateComputer(order).Resolve(
fail: () => {
new Job()
{
ActivationTime = order.ClientLocalStartTime,
ComputerName = order.ComputerName,
orderId = order.Id,
Status = invalidComputerErrorMessage,
}
},
success: () =>
{
var computer = GetComputer(order.ComputerName, order.CustomerId);
computer.CustomerId = GetCustomerId(order.CustomerId, computer.CustomerId);
var siteServerAddress = GetServerAddress(order.ComputerName, computer.CustomerId);
var deploymentType = GetDeploymentType(order.MaterialNumber, computer.CustomerId);
return new Job()
{
ActivationTime = order.ClientLocalStartTime,
ComputerName = order.ComputerName,
orderId = order.Id,
JobActions = CreateJobActions(deploymentType, order, siteServerAddress, computer),
Status = "created",
}
});
private Either ValidateComputer(Order order)
{
bool valid = !String.IsNullOrEmpty(order.ComputerName);
if (valid)
{
return new Success();
}
return new Fail();
}
#
# Either
#
public abstract class Either<TFail, TSuccess>
{
public abstract TResult Resolve<TResult>(Func<TFail, TResult> fail, Func<TSuccess, TResult> success);
public abstract TResult Resolve<TResult>(Func<TFail, TResult> fail, Action<TSuccess> success);
}
public class Fail<TFail, TSuccess> : Either<TFail, TSuccess>
{
private readonly TFail value;
public Fail(TFail value)
{
this.value = value;
}
public override TResult Resolve<TResult>(Func<TFail, TResult> fail, Action<TSuccess> success)
{
return fail(value);
}
}
public class Success<TFail, TSuccess> : Either<TFail, TSuccess>
{
private readonly TSuccess value;
public Success(TSuccess value)
{
this.value = value;
}
public override TResult Resolve<TResult>(Func<TFail, TResult> fail, Func<TSuccess, TResult> success)
{
return success(value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment