コメントは誤りです

あなたがプログラマーであるならば、あなたが嫌うことができる多くの慣行があります。





ハードコードされた値。ダブルロジック。複雑な継承階層。しかし、コメントはこのリストに含める必要がありますか?





昔、先史時代のプログラミングの時代には、コメントを書くことはコードを書くことの必須の部分と考えられていました。あなたがコードを書いたとき、それは短くて正確なコメントでいっぱいでした。その後、クリーンなコードとアジャイルプログラミングが世界を支配し始めました。純粋主義者は、構造化されていない脆弱なコードを埋めるコメントの危険性について叫びました。突然、コメントは間違い、アンチパターン、完全な嘘のコレクションになりました。





多くの開発者は追い詰められたと感じました。





誤った選択
誤った選択

しかし、その選択はそれほど明白ですか?それとも、コメントを書くと同時に、朝起きて自分を尊重する方法はありますか?答えを見つけるために、ひどいコードがどのようにコメントされているか、そして悪いコメントでさえどのように命を救うことができるかを見てみましょう。





怠惰なコメント

, , .





, , :





double delta = h*h-r1*r1;
double r2 = Math.Sqrt(delta);
      
      



, , . , , , :





// Calculate side length using the Pythagorean Theorem
// and put the value into variable "r2"
double delta = h*h-r1*r1;
double r2 = Math.Sqrt(delta);
      
      



- . .





. , :





double lengthSideB = Math.Sqrt(
  Math.Pow(hypotenuse,2) - Math.Pow(lengthSideA,2);
)
      
      



:





double sideA = Pythagoras.GetLengthOfSide(hyptenuse, sideB);
      
      



? ! - , , . , . , . - - .





. , , , . , - - . , , . , . , . :





/**
  * Constructor.
  * 
  * @param name (required) brand name of the product. Must have
  * content. Length must be in range 1..50. 
  * @param price (optional) purchase price of the product.
  * @param units (required) number of units currently in stock.
  * Can not be less than 0.
*/
public Product(string name, decimal price, integer units)
{
   ...
}
      
      



, , . - , . . , , .





. , . . . . , , - . API. , , . . - , . , API , , , . . , - . , . .





« - » - , .





. , - :





// to match ITG1's late arrows.  -K
GlobalOffsetSeconds=-0.006
      
      



, - , . - , , , , . , , , . . , , , . , - , , , , ? - , , , , , .





, , , , . , , , . , . - , - .





“I spent some time this weekend looking at very well-named, very clean, uncommented code implementing a research algorithm. I’m high-level familiar with it, the guy sitting next to me was the inventor, and the code was written a few years ago by someone else. We could barely follow it.” — Paul Nathan





, , . , , , . . , . , , . .





, . . :





  • ( )





  • ( )





  • ( IDE)





主な質問は簡単です。コメントにお金を払う価値はありますか?意見は異なりますが、コメントを慎重かつインテリジェントに使用する場合(悪い慣行に対抗するのではなく、コメントを使用してコードの認知的負荷を軽減する場合)、最もクリーンなコードにも価値を付加できます。












All Articles