混淆代码有时会有用吗?

Can obfuscated code be useful sometimes?

在 C# 中创建具有单精度坐标值的自定义 3D Point class 时,我必须编写一个方法来计算两点之间的距离。然后我想到 A -> B 表示 "from A to B" 的图形符号,我考虑重载 > 运算符,因为考虑点 A 比 "greater" 没有意义B点(此外,->运算符不能重载)。

所以我创建了以下方法:

/// <summary>
/// Calculates the Manhattan distance between the two points.
/// </summary>
public static float operator>(Point p1, Point p2)
{
    return Math.Abs(p1.X - p2.X) +
           Math.Abs(p1.Y - p2.Y) +
           Math.Abs(p1.Z - p2.Z);
}

/// <summary>
/// Calculates the euclidean distance between the two points.
/// </summary>
public static double operator>=(Point p1, Point p2)
{
    return Math.Sqrt(Math.Pow(p1.X - p2.X, 2) +
                     Math.Pow(p1.Y - p2.Y, 2) +
                     Math.Pow(p1.Z - p2.Z, 2));
}

这导致代码如下:

var manhattan = A > B;
var euclidean = A >= B;

代码看起来很混乱,但是一旦你掌握了它,它就很容易阅读,而且比使用 A.DistanceTo(B) 更短。

问题是,我应该完全避免这种代码吗?如果有,原因是什么?我非常关心 Clean Code,我不确定这是否可以被视为 clean。如果您认为有时允许这样的代码,您能否提供示例?

通常你应该避免这种代码(除非它可能是更深入的 DSL 的一部分)。

用意想不到的行为覆盖常见的运算符和方法会导致代码的拾取、理解和调试变得非常困难。

想象一下,你正在看一本书,虽然单词看起来像英文,但作者通过在后面的附录中做一些注释,改变了几个关键词的含义,所以你不断地来回翻阅检查每个句子的含义。

代码应该被编写成供人类阅读。你做这项任务越容易,你加入的惊喜越少,它就会越好。