优美的代码像诗一样!

网上曾有中日程序员代码风格的讨论,其实两种风格我都不喜欢。

让我们看看美国程序员是怎么做的吧。

以下摘自《代码阅读方法与实践》第2.9节P32-36。

第一段代码:

op = &( !x ? ( !y ? upleft : ( y == bottom ? lowleft : left)) :
( x == last ? ( !y ? upright : ( y == bottom ? lowright : right )) :
( !y ? upper : ( y == bottom ? lower : normal))))[ w -> orientation];

噢!但愿我没有打错。这段代码我足足看了十分钟也没明白究竟。


一般来说,可以改成下面这样。

struct options *locations[3][3] = {
  {upleft,     upper,     upright};
  {left,       normal,    right},
  (lowleft,    lower,     lowringt},
};

int xlocation, ylocation;

if (x == 0)
   xlocation = 0;
else if (x == last)
   xlocation = 2;
else
   xlocation =1;

if (y == 0)
   ylocation = 0;
else if (y == bottom)
   ylocation = 2;
else
   ylocation =1;

op = &(locations[ylocation][xlocation])[w->orientotion};

不过一个叫Guy Steele的提出了以下代码。

op =
   &(        ! y ?(x ? upleft  : x != last ?   uper : upright):
    y != bottom ? (x ? left    : x != last ? normal : right):
                  (x ? lowleft : x != last ? lower  : lowright):
    )[w -> orientation];

谁说代码的可读性和效率不能兼顾的。

你可能感兴趣的:(学习笔记)