【发布时间】:2016-04-03 20:46:05
【问题描述】:
如果:
- 代码没有直接面向 UI。它是 API 的一部分。
- 重要的是不要继续执行错误的参数。
- 我想要良好的可读性和流畅性。
我也考虑过返回一个验证对象,就像answer 中描述的那样,但是这种编程风格让我想起了GoLang functions handle errors 的方式。我认为例外是为了防止我们不得不这样做而发明的。
public void AddChildStructureLevel(Structure childStructureLevel)
{
try
{
TryPassNameValidation(childStructureLevel.Name); // throws if something is wrong
Children.Add(childStructureLevel);
}
catch (ArgumentException ae)
{
throw new ArgumentException($"Provided structure name {childStructureLevel.Name} is invalid.", ae);
}
Trace.WriteLine($"Added new child structure level to parent structure children.");
}
private void TryPassNameValidation(string structureName)
{
TryPassingStructureNameMinMaxLength(structureName);
TryPassingStructureNameUnique(structureName);
}
private void TryPassingStructureNameMinMaxLength(string structureName)
{
bool nameIsTooLong = structureName.Length >= maxLengthStructureName;
bool nameIsTooShort = structureName.Length <= minLengthStructureName;
if (nameIsTooLong) throw new ArgumentException($"Structure name is too long. Max {maxLengthStructureName} characters.");
if (nameIsTooShort) throw new ArgumentException($"Structure name is too short. Min {minLengthStructureName} characters.");
}
private void TryPassingStructureNameUnique(string childName)
{
foreach (Structure child in Children) //TODO: recurse over children.children
if (child.Name == childName) throw new ArgumentException($"Structure level name {childName} already exists.");
}
【问题讨论】:
-
我认为codereview.stackexchange.com 是更好的提问地点。
-
是的,尽管最终一切都还是基于意见的。但是,您的用例描述了大多数开发人员将使用异常的确切条件。
-
感谢 Valentin 的提示。甚至不知道它的存在。