TryParse 的这些控制流中的哪一个通常被建议,如果一个超过另一个?
Which of these control flows for TryParse is generally advised, if one over the other?
我有一个字符串 typeString
,我试图将其解析为包含 30 个案例的枚举,所有案例都有相当独特的 return 语句。在一些书中,我看到过这样的控制流程
if (!Enum.TryParse(typeString, true, out replicatingInstrumentType))
{
Log.Error("Unknown Replicating instrument type: " + typeString);
return new EmptyInstrument(instrumentIdentifier, Currency.EUR);
}
switch (replicatingInstrumentType)
{
case TypeA:
{
return TypeAReturnStatement;
}
// .....
// more cases here ....
// .....
case TypeZ:
{
return TypeZReturnStatement;
}
default:
{
return new EmptyInstrument(instrumentIdentifier, Currency.EUR);
}
}
而我一直认为应该这样做
if (Enum.TryParse(typeString, true, out replicatingInstrumentType))
{
switch (replicatingInstrumentType)
{
case TypeA:
{
return TypeAReturnStatement;
}
// .....
// more cases here ....
// .....
case TypeZ:
{
return TypeZReturnStatement;
}
default:
{
return new EmptyInstrument(instrumentIdentifier, Currency.EUR);
}
}
}
Log.Error("Unknown Replicating instrument type: " + typeString);
return new EmptyInstrument(instrumentIdentifier, Currency.EUR);
除了视觉上的差异,还有什么 advantage/disadvantage 使用一个与另一个不同的地方吗?是否就哪种方法更好达成共识?
if (!Enum.TryParse(typeString, true, out replicatingInstrumentType))
{
Log.Error("Unknown Replicating instrument type: " + typeString);
return new EmptyInstrument(instrumentIdentifier, Currency.EUR);
}
它被称为Inverted IF
或Replace Nested Conditional with Guard Clauses。它只是为了更容易阅读,因为它减少了嵌套和缩进的数量。较小的缩进会增加您的水平视图区域。
我有一个字符串 typeString
,我试图将其解析为包含 30 个案例的枚举,所有案例都有相当独特的 return 语句。在一些书中,我看到过这样的控制流程
if (!Enum.TryParse(typeString, true, out replicatingInstrumentType))
{
Log.Error("Unknown Replicating instrument type: " + typeString);
return new EmptyInstrument(instrumentIdentifier, Currency.EUR);
}
switch (replicatingInstrumentType)
{
case TypeA:
{
return TypeAReturnStatement;
}
// .....
// more cases here ....
// .....
case TypeZ:
{
return TypeZReturnStatement;
}
default:
{
return new EmptyInstrument(instrumentIdentifier, Currency.EUR);
}
}
而我一直认为应该这样做
if (Enum.TryParse(typeString, true, out replicatingInstrumentType))
{
switch (replicatingInstrumentType)
{
case TypeA:
{
return TypeAReturnStatement;
}
// .....
// more cases here ....
// .....
case TypeZ:
{
return TypeZReturnStatement;
}
default:
{
return new EmptyInstrument(instrumentIdentifier, Currency.EUR);
}
}
}
Log.Error("Unknown Replicating instrument type: " + typeString);
return new EmptyInstrument(instrumentIdentifier, Currency.EUR);
除了视觉上的差异,还有什么 advantage/disadvantage 使用一个与另一个不同的地方吗?是否就哪种方法更好达成共识?
if (!Enum.TryParse(typeString, true, out replicatingInstrumentType))
{
Log.Error("Unknown Replicating instrument type: " + typeString);
return new EmptyInstrument(instrumentIdentifier, Currency.EUR);
}
它被称为Inverted IF
或Replace Nested Conditional with Guard Clauses。它只是为了更容易阅读,因为它减少了嵌套和缩进的数量。较小的缩进会增加您的水平视图区域。