我有一些几周前写的代码(代码的目的不如它的结构重要):
if (_image.Empty)
{
//Use the true image size if they haven't specified a custom size
if (_glyphSize.Width > 0)
imageSize.Width = _glyphSize.Width //override
else
imageSize.Width = _image.GetWidth;
if (_glyphSize.Height > 0) then
imageSize.Height = _glyphSize.Height
else
imageSize.Height = _image.GetHeight
}
else
{
//No image, but they can still override it with a custom size
if (_glyphSize.Width > 0) then
imageSize.Width = _glyphSize.Width
else
imageSize.Width = 0;
if (_glyphSize.Height > 0)
imageSize.Height = _glyphSize.Height
else
imageSize.Height := 0;
}
今晚我正在检查它,当我清理它时,我意识到清理后的版本必须更简洁:
//Figure out the final image width
if (_glyphSize.Width > 0)
imageSize.Width = _glyphSize.Width
else if (not _glyph.Empty)
imageSize.Width = _glyph.GetWidth
else
imageSize.Width = 0;
//Figure out the final image height
if (_glyphSize.Height > 0)
imageSize.Height = _glyphSize.Height
else if (not _glyph.Empty)
imageSize.Height = _glyph.GetHeight
else
imageSize.Height = 0;
注意:我已将代码精简为裸露的逻辑流程,并混淆了源语言。
最后,我采用了嵌套if
的 's,并将它们倒置。这样做允许这种缩短。我的问题是:我以后如何才能认识到这一点?
有什么迹象表明我刚刚编写了一些可以重构为更短代码的代码?
几周前的另一个例子类似于权限检查:用户可以执行一个操作:
- 如果他们有许可,他们可以这样做
- 如果他们没有权限,但覆盖有效
我最初编码为:
if ((HasPermission || (!HasPermission and OverrideEnabled))
{
...do stuff
}
该if
条款的逻辑条件似乎有点冗长。我试图回到我的布尔代数课程来弄清楚如何简化它。最后我可以做到,所以我最终绘制了一个真值表:
Permission Override Result
0 0 0
0 1 1
1 0 1
1 1 1
当我看它时,它是一个OR操作。所以我的if
声明变成了:
if (HasPermission or OverrideEnabled)
{
...
}
这是显而易见的和简单的。所以现在我想知道我怎么看不到这一点。
这让我回到了我的 SO 问题:为了识别某些代码块需要一些 TLC,我可以/应该寻找什么迹象?