Inline comments within code are “evil” and everybody who still uses inline comments today is a really, really bad developer and should get his license revoked. That’s what seems to be consensus throughout the developer community … or at least throughout the “up to date” community.
Okay, but I say that we need more inline comments. So, what’s wrong with me? Have I gone completely nuts?
Now, while answering the last two questions might be a difficult task …
… my idea about inline comments is quite straightforward:
If you want to understand any kind of solution, i.e. whenever you need to implement some new feature within an existing, yet unknown code base, you need at least three essential questions to be answered:
- Why?
- What?
- How?
So, how will you get these questions answered without having the original developer at hand?
- The “How” is simple. That is the code in itself. Thus, it definitely makes sense to write the code as understandable as possible that everybody else will understand the “How” as easy as possible.
- The “What” is usually the domain of the class/method/function/… header. The comment header describes “What” the piece of code down below is meant to do. In Java that is the domain of the Javadoc, other programming languages have their own means or conventions for that.
- But where is the “Why”? The code itself cannot answer the question for obvious reasons and the Javadoc, etc. is not meant for this. It has to focus on the “What”. You could put the “Why” part to a separate artifact, an extra document, i.e. a design document or whatever. But that is quite cumbersome. Also there is a high probability that any changes, refactorings, etc. in the code wouldn’t find their way into that document so that it becomes obsolete quite fast. Hence, it would be better to place the answers to the “Why” questions right at the place where you can see the effect of the corresponding decision, right next to the code that shows “How” the decision of the “Why” question was implemented.
That’s where inline comments come in handy. They provide a perfect means to describe rationale for certain decisions that you find within the code. Whenever you think “Why the heck did he or she implement that piece of code this way?” it would be just perfect to find an inline comment right next to the piece of code that answers that question, wouldn’t it? But today most of the time you will look in vain for those answers. Instead you might have to ask the original developer if he or she is still around and remembers that decision or that knowledge is gone for good and you have to guess the rationale.
Thus, for me the domain of inline comments is answering “Why” questions and from my experience from a maintainability and changeability perspective (that’s where the architect inside kicks in
) understanding the “Why” is often a lot more important than understanding the “What” … and the “How” is laid out in the source code anyway.
That’s the reason why I say that we need more inline comments
- not for explaining the “What”, that’s the domain of the header comments
- not for explaining the “How”, the code should answer that by itself
- but for answering those “Why” questions, to provide the rationale for design and implementation decisions that are missing most of the time
Therefore here’s my concluding tip for you:
Kick that rule off your coding standard that says
“You are not allowed to use inline comments”
and replace it with
“You should use inline comments only to explain (non-obvious) design and implementation decisions (“Why” questions) … and don’t forget to use them for this purpose!”
category:
English
Deutsch 

An die Regel
“Du darfst keine Inline-Kommentare verwenden”
habe ich mich nie gehalten. Allein formal lässt sich eben nicht alles mit JavaDocs (oder äquivalenten Kommentarformen in anderen Sprachen) ausdrücken, sofern man nicht eine Unmenge an Methoden schreibt.
Also: volle Zustimmung!
I agree on the point of having a strict policy on no inline comments is silly, as with most other strict coding policies.
Of course, you should strive to avoid non-obvious code in the first place. Inline comments shouldn’t be an excuse for getting away with writing crap code.
I might be referencing the Clean Code book here: A method should contain instructions that work on the same level of abstraction. If you’re mixing non-obvious code with obvious code in the same method, chances are that the method is trying to do too many different things.
Whenever I feel the itch to write an inline comment, I consider that the next few lines could probably be extracted into a private method. I then describe the reasoning in the JavaDoc of this extracted method. If I just want to comment on a one-liner, it’s fine to do so inline.
+1 with some tiny “buts”
I like the separation into What, How, Why – it’s very catchy. However, my very personal “golden rule” about inline comments goes slightly different:
First, by all means write your code in a way that is so simple and obvious that it does not need to be commented. While writing a comment for a non-obvious design decision, ask yourself: Could I do that with a simpler design which is more obvious? (Of course, you could/should have asked that before, but sometimes for me it’s only when I try to explain the solution that I recognize that it is, well, sub optimal…)
Second, only if that fails, use comments. But then, by all means, use them and write clear and comprehensible.
But perhaps this is just another wording for the same thoughts.
Another aspect regarding comments that comes to my mind. If you follow the Uncle Bob’s advises from the book Clean Code, you end up writing a lot of very small methods. In this approach, the method name often plays takes the role of a comment in lengthier methods. This helps a lot with writing self-explanatory code.
Just my 2 cents…
====
Die Aufteilung in Was, Wie und Warum gefällt mir gut ist schön plakativ und einprägsam. Allerdings lautet die (ganz persönliche) goldene Regel, die sich in meinem Kopf zum Thema Inline-Kommentare eingenistet hat, leicht anders:
Priorität 1: Den Code wann immer möglich so schreiben, dass das “Warum” offensichtlich ist und keiner weiteren Kommentierung bedarf. (Spätestens) wenn man dabei ist, eine nicht-offensichtliche Design-Entscheidung zu kommentieren, sollte man sich fragen, ob es nicht doch auch einfacher geht.
(Hätte man sich natürlich schon früher fragen können/sollen, aber ich persönlich merke manchmal erst in dem Moment, in dem ich versuche, die Lösung zu erklären, dass sie nicht das Gelbe vom Ei ist.)
Priorität 2: Nur wenn das nicht geht, sollte man auf Kommentare zurückgreifen – die dann natürlich möglichst klar und verständlich formuliert sein sollten.
Ist aber vielleich auch nur ein anderes Wording…
Noch ein Aspekt, der mir dazu einfällt: Wenn man sich an den Vorschlägen aus Uncle Bobs “Clean Code” hält und viele sehr kleine Methoden schreibt, die recht wenig tun, übernimmt der Methodenname oft die Funktion dessen, was man bei längeren Methoden möglicherweise als Kommentar dazuschreiben würde. Das bringt das ganze schon mal ein gutes Stück in Richtung “selbsterklärend”.
Bislang habe ich von einer Regel “Du darfst keine Inline-Kommentare verwenden” noch nichts gehört, was vielleicht daran liegt, dass ich offensichtlich kein Mitglied dieser wahnsinnig up-to-daten Entwicklergemeinde bin (vielleicht klärt mich ja noch jemand auf, wer das eigentlich ist.).
Irgendwie bekräftigt es zwar mein Vorurteil, dass dort zu viele (Hobby-)Ingenieure und zu wenig erfahrene Handwerker zu Gange sind und daher zuviel akademisiert wird und zu wenig praktische Erfahrung einfliesst. Aber bei genauerer Betrachtung diverser populärer Design- und Implementierungs-Prinzipien (cleancode, dry etc.) ist fehlende Inline Doku doch nur konsequent. Die Erstellung des Quellcodes sollte ja eigentlich objektiv nachvollziehbaren Mustern folgen, das warum ist dann also inhärent vorhanden.
Dennoch kann ich konsequente (Inline-)Dokumentation nur anraten, denn
-Man hat auch mal einen schlechten Tag und wählt nicht den einfachsten Weg einer Implemetierung.
-Man hat auch mal einen guten Tag und möchte den Jungs zeigen was man drauf hat.
-Unterschiedliche Kenntnis der Problemdomäne lassen ein und denselben Code anders erscheinen.
-Als Entwickler berücksichtigt man Dinge, die sich in keiner Spezifikation wiederfinden, weil man auch eigene Erfahrungen miteinbringt.
-*Moderne* Sprachkonstrukte haben mittlerweile eine Komplexität, die sich nicht unbedingt auf den 1. Blick erschliesst.
-Wenn der Code schon ein wenig lebt, leidet (allen guten Vorsätzen zum trotz) die Qualität, oftmals ja sogar während der primären Entwicklungsphase.
Also, solange wir nicht in einer vollkommen formalisierten Welt leben, ist es gar nicht verkehrt wenn der Autor aufschreibt, was er sagen will.
Hi,
thanks for the great comments up to now. I totally agree with your remarks about clean code, etc. Often it is possible to avoid inline comments using a different design and sometimes it makes sense to use inline comments for other reasons.
Yet my point was slightly different when talking about the “Why”. For an example: Some years ago I had to implement some _very_ strange stuff due to a bug in the DBMS we used. Without any comment the next developer would definitely thought that I had a _really_ bad day when coding that stuff because he wouldn’t have known “why” I did that. Especially he or she wouldn’t have known if that piece of code could be altered or not. Thus, even with the best design (that you should definitively should strive for) the “Why” is not always obvious without explaining it explicitly.
So, the problem is often not understanding what the code does. The problem is to know if you can change that code without breaking the system. That’s why you see so often workarounds around non-understood code in existing systems, even if they were designed very well in the beginning.
Ah, and testing does only solve that issue partially …
Regards, Uwe
———————————————————–
Hallo,
vielen Dank für die bisherigen sehr guten Kommentare. Ich stimme voll mit Euren Anmerkungen bzgl. Clean Code, usw. überein. Oftmals ist es möglich, Inline-Kommentare zu vermeiden, indem man ein anderes Design verwendet. Und manchmal macht es aus anderen Gründen absolut Sinn, Inline-Kommentare zu verwenden.
Dennoch hatte ich etwas leicht anderes im Kopf, als ich über das “Warum” geschrieben habe. Ein Beispiel: Vor einigen Jahren musste ich eine _ziemlich_ schräge Sache implementieren, weil unser DBMS einen Fehler hatte. Ohne einen Kommentar hätte der nächste Entwickler sicher gedacht, dass ich einen _echt_ schlechten Tag gehabt hatte, als ich das geschrieben habe. Insbesondere hätte er oder sie nicht gewusst, ob dieser Code geändert werden kann oder nicht. Deshalb ist auch mit dem besten Design (etwas, das man auf jeden Fall anstreben sollte) das “Warum” nicht immer klar, wenn man es nicht explizit erklärt.
Das Problem ist häufig nicht zu verstehen, was der Code tut. Das Problem ist vielmehr zu wissen ob man den Code ändern kann, ohne das System kaputt zu machen. Deshalb sieht man so häufig Workarounds um nicht verstandenen Code in existierenden Systemen, selbst wenn sie initial richtig gut designed worden sind.
Ah, und Testen löst dieses Problem auch nur teilweise …
Gruß, Uwe
So ganz kann ich diesen Kommentar nicht nachvollziehen. Soll das heißen, dass Kommentare eher dazu dienen die Sicherheit zu haben, dass man bei Änderung ein bestehendes System nicht kaputt macht ?
Kommentare sind die ersten die veraltet sind und es auch bleiben. Code wird geändert, Kommentare aber (leider) selten nachgezogen. Hierfür sind Tests ein wesentlich besserer und sicherer Mechanismus. Wenn Tests nicht ein Systemfehler aufdecken sind die Tests fehlerhaft.
Womöglich habe ich etwas falsch verstanden, doch sich auf Kommentare zu verlassen um die Integrität eines Systems zu sichern halte ich für gefährlich.
Hallo Emerson,
vielleicht zur Klarstellung: Es ging mir nie darum zu sagen, dass Kommentare besser oder schlechter als Tests geeignet sind, die Integrität des Systems sicherzustellen. Insbesondere bin ich auch ein klarer Befürworter von (automatisierten) Tests. Daher ja, Kommentare zur Sicherstellung der Systemintegrität halte ich ebenfalls für gefährlich.
Ich habe nur ein Problem mit Schwarz/Weiß-Dogmen. Entweder ist irgendetwas gaaanz toll oder gaaanz schlimm. In diesem Fall waren es die Inline-Kommentare, die Opfer der Verteufelung bestimmter “hipper” Gruppen geworden sind. “Wer Inline-Kommentare braucht, kann nicht vernünftig programmieren”, so die mehr oder weniger explizite Aussage an diversen Ecken.
Einer solchen Pauschalaussage muss ich einfach widersprechen, weil ich der Überzeugung bin, dass Inline-Kommentare ein hervorragendes Mittel sind, um die Idee hinter einer bestimmten Implementierung zu vermitteln, eben um “Warum”-Fragen zu beantworten.
An der Stelle nützen Tests leider auch nichts. Ein Test beantwortet mir nicht, warum jemand seinen Code an einer Stelle genau in der vorliegenden Form umgesetzt hat, er beantwortet mir nur, was das gewünschte Verhalten ist. Das hilft mir aber im Zweifelsfall auch nicht weiter, wenn ich wissen möchte, warum etwas in der vorliegenden Form programmiert worden ist und ob ich das (ggf. inklusive zugehörigem Test) ändern kann.
So gesehen: Ja, Test sind ein wichtiges Mittel, um die korrekte Funktionsweise einer Anwendung zu überprüfen, aber sie helfen einem nicht bei Warum-Fragen.
Gruß, Uwe
PS: Nebenbei gibt bei aller unbestrittenen Nützlichkeit von Tests trotzdem noch ein paar weitere Einschränkungen und Probleme, die gerne mal unter den Teppich gekehrt werden, auch in Bezug auf die problemlose Änderbarkeit und Überprüfbarkeit der Systemintegrität, aber das ist vielleicht mal ein Thema für einen anderen Post …