clean code裡面有提到,越多的註解代表程式寫得越差。
最近一直在體會這句話的涵意,讓我們來看看下面的例子:
bool bo = Dic.TryGetValue("hello",out val); if (bo) Console.WriteLine("do something");
從上面的例子我們知道當bo為true時,我們必須 do something。
再看看下面的例子:
bool HasKey = Dic.TryGetValue("hello",out val); if (HasKey) Console.WriteLine("do something");
上面的例子讓我們感覺像是在讀文章
first, we get a variable HasKey and then if it hsa key we will do something.
接著我們再看一段簡單的程式:
int x = 0; int y = 0; int z =0; while (z < 3) { if (IsTrue()) x++; else y++; if (x == 3) x_event(); if (y == 4) { y_event(); } }
我是故意寫那麼醜的,我相信大多數的人看完都只有一個感想 WhatThe....
接著我們再看看修改過的程式:
static int Three_People_Out =3; int Strike = 0; int ball = 0; int out_People =0; while (out_People < Three_People_Out) { if (IsInStrikeZone()) Strike++; else ball++; if (Strike == 3) StrikeOut(); if (ball == 4) { base_on_balls(); } }
相信看到修改過的程式應該可以看出這是在寫有關棒球的程式。
if IsInStrikeZone 則 好球++ 否則壞球++
if 三好球 則 StrikeOut
if 四壞球 則 保送 ...
善用命名可以讓我們不需要使用大量的註解,卻可以寫出可讀性高的程式。
命名真是一門藝術!!
沒有留言:
張貼留言