可靠的答案
这是绝对可以接受的:.NET 源代码包装了条件。
例如,StringBuilder
源代码有一个VerifyClassInvariant()
调用了 18 次的方法。该方法只是检查正确性。
private void VerifyClassInvariant()
{
BCLDebug.Correctness((uint)(m_ChunkOffset + m_ChunkChars.Length) >= m_ChunkOffset, "Integer Overflow");
StringBuilder currentBlock = this;
int maxCapacity = this.m_MaxCapacity;
for (; ; )
{
// All blocks have copy of the maxCapacity.
Contract.Assert(currentBlock.m_MaxCapacity == maxCapacity, "Bad maxCapacity");
Contract.Assert(currentBlock.m_ChunkChars != null, "Empty Buffer");
Contract.Assert(currentBlock.m_ChunkLength <= currentBlock.m_ChunkChars.Length, "Out of range length");
Contract.Assert(currentBlock.m_ChunkLength >= 0, "Negative length");
Contract.Assert(currentBlock.m_ChunkOffset >= 0, "Negative offset");
StringBuilder prevBlock = currentBlock.m_ChunkPrevious;
if (prevBlock == null)
{
Contract.Assert(currentBlock.m_ChunkOffset == 0, "First chunk's offset is not 0");
break;
}
// There are no gaps in the blocks.
Contract.Assert(currentBlock.m_ChunkOffset == prevBlock.m_ChunkOffset + prevBlock.m_ChunkLength, "There is a gap between chunks!");
currentBlock = prevBlock;
}
}
对话
可以将断言或异常分组到静态方法中,而不是显式地写出来吗?
是的。没关系。
...这似乎违背了先决条件应该有助于记录方法的确切意图的想法。
assert
包装or语句的方法的名称Exception
应该传达包装器的意图。另外,如果读者想知道细节,那么她可以查看该方法的实现(除非它是闭源的。)
这被认为是好的还是坏的做法,为什么?
将一组相关或经常重用的方法包装asserts
在另一种方法中是一种很好的做法,因为它既可以提高可读性又便于维护。
这是一种常见的反模式吗?
恰恰相反。您可能会看到类似这样的内容,它实际上很有帮助并被推荐,因为它可以很好地沟通。
private void IfNotValidInputForPaymentFormThenThrow(string input)
{
if(input.Length < 10 || input.Length)
{
throw new ArgumentException("Wrong length");
}
// other conditions omitted
}
ThenThrow
添加到方法的末尾是一个好主意,以便调用者知道您正在抛出。否则,您可能希望返回 abool
并让调用者决定如果条件失败该怎么办。
private bool IsValidInputForPaymentForm(string input)
{
if(input.Length < 10 || input.Length)
{
return true;
}
else
{
return false;
}
// other conditions omitted
}
然后调用代码可以抛出:
if(!IsValidInputForPaymentForm(someStringInput)
{
throw new ArgumentException();
}
或者,这是.NET 源代码中的另一个示例,如果某些条件失败,则会引发异常(ThrowHelper
只是引发异常。)
// Allow nulls for reference types and Nullable<U>,
// but not for value types.
internal static void IfNullAndNullsAreIllegalThenThrow<T>(
object value, ExceptionArgument argName)
{
// Note that default(T) is not equal to null
// for value types except when T is Nullable<U>.
if (value == null && !(default(T) == null))
ThrowHelper.ThrowArgumentNullException(argName);
}
有什么重要的理由不这样做吗?
我能想到的是,如果方法名称没有解释您正在检查的内容,并且没有简单的方法来查看源代码,那么您可能应该避免包装条件。