我已经开始使用 C# 7 的基于类型的模式匹配。只管理单个基于模式的结果的方法看起来非常干净且易于推理。
但是,一旦依赖于第一个基于模式的结果的第二个基于模式的结果创建了一个箭头反模式,并且只会在 n 个结果相互依赖时变得更糟。
这是一个演示箭头模式的简化示例:
public Result<bool> ValidateSomething(string strId)
{
var id = Guid.Parse(strId);
Result<Something> fetchSomethingResult = new SomethingDao.FetchSomething(id);
switch (fetchSomethingResult)
{
case ValueResult<Something> successfulSomethingResult:
Result<Related> fetchRelatedFieldsResult = new RelatedDao.FetchRelatedFields(successfulSomethingResult.Value.RelatedId);
switch (fetchRelatedFieldsResult)
{
case ValueResult<Related> successfulFieldValueResult:
var isValid = successfulSomethingResult.Value.ComparableVal <= successfulFieldValueResult.Value.RelatedComparableVal;
return new ValueResult<bool>(isValid);
case ValueNotFoundResult<Related> _:
return new ValueNotFoundResult<bool>();
case ErrorResult<Related> errorResult:
return new ErrorResult<bool>(errorResult.ResultException);
default:
throw new NotImplementedException("Unexpected Result Type Received.");
}
case ValueNotFoundResult<Something> notFoundResult:
return new ValueNotFoundResult<bool>();
case ErrorResult<Something> errorResult:
return new ErrorResult<bool>(errorResult.ResultException);
default:
throw new NotImplementedException("Unexpected Result Type Received.");
}
}
作为参考,这些是Result类的定义:
public abstract class Result<T>
{
}
public class ValueResult<T> : Result<T>
{
public ValueResult()
{
}
public ValueResult(T inValue)
{
Value = inValue;
}
public T Value { get; set; }
}
public class ValueNotFoundResult<T> : Result<T>
{
public ValueNotFoundResult()
{
}
}
public class ErrorResult<T> : Result<T>
{
public Exception ResultException { get; set; }
public ErrorResult()
{
}
public ErrorResult(Exception resultException)
{
ResultException = resultException;
}
}
有哪些选项可以更好地处理此类代码?你对前面的例子有什么建议?如何使用基于模式的结果避免箭头反模式?