Статьи

5 лучших практик для комментирования вашего кода

Одна из первых вещей, которые вы учитесь делать неправильно, когда программист комментирует ваш код. Мой опыт работы со студентами и недавно окончившими программисты говорит мне, что колледж — действительно хорошее место для изучения действительно плохих методов комментирования кода. Это только одна из тех областей, где теоретические и практические аспекты не очень хорошо совпадают.

Есть два фактора, которые мешают вам изучать хорошую технику комментирования в колледже.

  1.  В отличие от реального мира, вы делаете много маленьких одноразовых проектов в качестве индивидуального разработчика. Никто не мечтает о том, чтобы бросить на тебя валун, чтобы он расшифровал твое злодеяние в коде.
  2.  Такой стиль комментирования, который вы эмулируете из своего учебника, является хорошей практикой только тогда, когда комментарии предназначены для обучения студентов программированию. Это прямо раздражает профессиональных программистов.

Эти советы в первую очередь предназначены для начинающих программистов, которые переходят в реальный мир программирования, и, мы надеемся, некоторые из них не будут выглядеть так во время своего первого обзора кода. Обзор кода? О, да, это то, что они не учили вас в школе, но это совсем другая статья, я буду откладывать на эту тему Джейсона Коэна .

Итак, начнем …

(1) Комментарии не являются субтитрами

Легко спроецировать свое собственное мировоззрение, что код — это иностранный язык, понятный только компьютерам, и что вы предоставляете читателю услугу, объясняя, что делает каждая строка в той или иной форме человеческого языка. Или, возможно, вы делаете это в интересах того непрограммистского менеджера, который наверняка захочет прочитать ваш код (Спойлер: Он не будет).

Послушайте, в не столь отдаленном будущем вы сможете читать код почти так же легко, как ваш родной язык, и все остальные, кто даже взглянет на него, почти наверняка уже смогут. К тому времени вы поймете, как глупо писать такие комментарии:

// Loop through all bananas in the bunch
foreach(banana b in bunch) {
    monkey.eat(b);  //make the monkey eat one banana
}

Возможно, вас научили программировать, сначала записывая комментарии псевдокода, а затем записывая реальный код в этот каркас. Это совершенно разумный подход для начинающего программиста. Обязательно замените комментарии кодом и не оставляйте их там.

Компьютер: враг соответствует скорости.
Гвен Демарко: Враг соответствует скорости!
Сэр Александр Дейн: Мы слышали это впервые!
Гвен Демарко: Черт возьми, я делаю это. Я повторяю проклятый компьютер!

-Galaxy Quest

Исключения:

  • Примеры кода, используемые для обучения концепции или нового языка программирования.
  • Языки программирования, которые не читаются человеком на расстоянии (Assembly, Perl)

(2) Комментарии не являются арт-проектом

This is a bad habit propagated by code samples in programing books and open source copyright notices that are desperate to make you pay attention to them.

/*
   _     _      _     _      _     _      _     _      _     _      _     _
  (c).-.(c)    (c).-.(c)    (c).-.(c)    (c).-.(c)    (c).-.(c)    (c).-.(c)
   / ._. \      / ._. \      / ._. \      / ._. \      / ._. \      / ._. \
 __\( Y )/__  __\( Y )/__  __\( Y )/__  __\( Y )/__  __\( Y )/__  __\( Y )/__
(_.-/'-'\-._)(_.-/'-'\-._)(_.-/'-'\-._)(_.-/'-'\-._)(_.-/'-'\-._)(_.-/'-'\-._)
   || M ||      || O ||      || N ||      || K ||      || E ||      || Y ||
 _.' `-' '._  _.' `-' '._  _.' `-' '._  _.' `-' '._  _.' `-' '._  _.' `-' '._
(.-./`-'\.-.)(.-./`-'\.-.)(.-./`-'\.-.)(.-./`-'\.-.)(.-./`-'\.-.)(.-./`-'\.-.)
 `-'     `-'  `-'     `-'  `-'     `-'  `-'     `-'  `-'     `-'  `-'     `-'

                 -It's Monkey Business Time! (Version 1.5)
*/

Why, that’s silly. You’d never do something so silly in your comments.

ORLY? Does this look familiar?

+------------------------------------------------------------+
 | Module Name: classMonkey                                  |
 | Module Purpose: emulate a monkey                          |
 | Inputs: Bananas                                           |
 | Outputs: Grunts                                           |
 | Throws: Poop                                              |
+------------------------------------------------------------+

Programmers love to go “touch up” their code to make it look good when their brain hurts and they want something easy to do for a while. It may be a waste of time, but at least they are wasting it during periods where they wouldn’t be productive anyway.

The trouble is that it creates a time-wasting maintenance tax imposed on anyone working with the code in the future just to keep the pretty little box intact when the text ruins the symmetry of it. Even programmers who hate these header blocks tend to take the time to maintain them because they like consistency and every other method in the project has one.

How much is it bugging you that the right border on that block is misaligned? Yeah. That’s the point.

(3) Header Blocks: Nuisance or Menace?

This one is going to be controversial, but I’m holding my ground. I don’t like blocks of header comments at the top of every file, method or class.

Not in a boat, not with a goat.
Why? Well let me tell you, George McFly…

They are enablers for badly named objects/methods – Of course, header blocks aren’t the cause for badly named identifiers, but they are an easy excuse to not  put in the work to come up with meaningful names, an often deceptively difficult task. It provides too much slack to just assume the consumer can just read the “inline documentation” to solve the mystery of what the DoTheMonkeyThing method is all about.

JohnFx’s Commandment:
The consumer of thy code should never have to see its source code to use it, not even the comments.

They never get updated: We all know that methods are supposed to remain short and sweet, but real life gets in the way and before you know it you have a 4K line class and the header block is scrolled off of the screen in the IDE 83% of the time. Out of sight, out of mind, never updated.

The bad news is that they are usually out of date. The good news is that people rarely read them so the opportunity for confusion is mitigated somewhat. Either way, why waste your time on something that is more likely to hurt than help?

JohnFx’s Maxim of Plagiarized Ideas :
Bad Documentation is worse than no documentation.

Exception: Some languages (Java/C#) have tools that can digest specially formatted header block comments into documentation or Intellisense/Autocomplete hints. Still, remember rule (2) and stick to the minimum required by the tool and draw the line at creating any form of ASCII art.

(4) Comments are not source control

This issue is so common that I have to assume that programmers (a) don’t know how to use source control; or  (b) don’t trust it.

Archetype 1: “The Historian”

// method name: pityTheFoo (included for the sake of redundancy)
// created: Feb 18, 2009 11:33PM
// Author: Bob
// Revisions: Sue (2/19/2009) - Lengthened monkey's arms
//            Bob (2/20/2009) - Solved drooling issue
	 
	void pityTheFoo() {
     ...
}

The programmers involved in the evolution of this method probably checked this code into a source control system designed to track the change history of every file, but decided to clutter up the code anyway. These same programmers more than likely always leave the Check-In Comments box empty on their commits.

I think I hate this type of comment worst of all, because it imposes a duty on other programmers to keep up the tradition of duplicating effort and wasting time maintaining this chaff. I almost always delete this mess from any code I touch without an ounce of guilt. I encourage you to do the same.

Archetype 2: “The Code Hoarder”

void monkeyShines() {
    if (monkeysOnBed(Jumping).count > max) {
        monkeysOnBed.breakHead();
 
	        // code removed, smoothie shop closed.
	        // leaving it in case a new one opens.
	        // monkeysOnBed.Drink(BananaSmoothie);
   }
	}

Another feature of any tool that has any right to call itself a SCM is the ability to recover old versions of code, including the parts you removed. If you want to be triple super extra sure, create a branch to help you with your trust issues.

(5) Comments are a code smell

Comments are little signposts in your code explaining it to future archaeologists that desperately need to understand how 21st century man sorted lists of purchase orders.

Unfortunately, as Donald Norman explained so brilliantly in The Design of Everyday Things, things generally need signs because their affordances have failed. In plain English, when you add a comment you are admitting that you have written code that doesn’t communicate its purpose well.

Sign:»This is a mop sink.» Why would that be necces… oh.

Despite what your prof told you in college, a high comment to code ratio is not a good thing.  I’m not saying to avoid them completely, but if you have a 1-1 or even a 5-1 ratio of LOC to comments, you are probably overdoing it. The need for excessive comments is a good indicator that your code needs refactoring.

Whenever you think, “This code needs a comment” follow that thought with, “How could I modify the code so its purpose is obvious?”
Talk with your code, not your comments.

Technique 1: Use meaningful identifiers and constants (even if they are single use)

// Before
 // Calculate monkey's arm length
 // using it's height and the magic monkey arm ratio
 double length = h * 1.845; //magic numbers are EVIL!
	 
// After - No comment required
double armLength = height * MONKEY_ARM_HEIGHT_RATIO;

Technique 2: Use strongly typed input and output parameters

// Before
	 
 // Begin: flip the "hairy" bit on monkeys
	 foreach(monkey m in theseMonkeys) {
	     // 5-6 steps to flip bit.
	 }
 // End: flip the "hairy" bit on monkeys
	 
// After No comment required
flipHairyBit(theseMonkeys);

As an added bonus, technique 3 will tend to reduce the size of your methods and minimizing the nesting depth (see also “Flattening Arrow Code”) all of which contribute to eliminating the need for commenting the closing tags of blocks like this:

     } // ... if see evil
    } // .. . while monkey do.
   } // ... if monkey see.
  } // ... class monkey
} // ... namespace primate

Acknowledgments

Several of the ideas presented here, and a good deal of the fundamental things I know about programming as part of a team, and not as a lone-wolf working on a college project I learned from the book Code Complete by Steve McConnell. If you are a working programmer and have not read this book year, stop what you are doing and read it before you write another line of code.

 

 

From  http://improvingsoftware.com/2011/06/27/5-best-practices-for-commenting-your-code/