【发布时间】:2020-10-04 22:31:40
【问题描述】:
我已经开始使用基于 C# 7 的类型pattern matching。只管理单个基于模式的结果的方法看起来非常干净且易于推理。
但是,一旦依赖于第一个基于模式的结果的第二个基于模式的结果会创建一个箭头反模式,并且只会在 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;
}
}
有哪些选项可以更好地处理此类代码?你对前面的例子有什么建议?如何在基于模式的结果中避免箭头反模式?
【问题讨论】:
-
您可以在单独的方法中移动嵌套的方法(它们可以是本地方法)。
-
我觉得还是在codereview.stackexchange.com问比较好
-
您可以将开关逻辑提取到处理错误、未找到和默认情况的方法中,方法相同,并允许您传入
Func<T, Result<bool>>来处理成功情况。跨度> -
谢谢@PavelAnikhouski。我在那里提出了一个重复的问题。 (codereview.stackexchange.com/questions/243934/…)
-
@PavelAnikhouski the code above appears to be too hypothetical 用于代码审查。在推荐用户在那里发帖之前,请先熟悉on-topic 的 CR 是什么
标签: c# oop .net-core pattern-matching