SlideShare una empresa de Scribd logo
1 de 2
Descargar para leer sin conexión
Y
OUR CODE READING SPEED IS AFFECTED
by many factors, some of which depend
on you, some of which depend on the code.
For instance, your ability to parse and grasp
code will be lower in the post-lunch siesta part of
the afternoon than during the up-’n’-at-’em,
caffeine-injected start of the day. You can grasp code
more rapidly and accurately when it is based on
familiar patterns rather than someone else’s
programming idiolect. Reading through long-
winded or poorly constructed logic and control flow
is more akin to wading through molasses than
cutting through butter. However, super-clever
code trickery or cryptic conventions keep you
guessing. And then there are comments.
Comments should improve the readability of
the code, but so often, the opposite is true. As with
so many shoulds in life, it takes more than just saying
it to get it right. Comments are an odd form of code:
they are code that is not code. They are bound by
a formal syntax but, with the exception of particular
annotations for certain tools, comments are not read
by compilers. Hmm, for that matter, they are not
really read by programmers.
Goldilocks and the three
programmers
When it comes to estimating the value of comments,
there are three basic schools of thought: any
comment is a good comment; any comment is a
bad comment; only comments that communicate
are good, all the rest are bad. This is a bit like
Goldilocks with her porridge pilfering: too hot, too
cold, just right.
The view that all code should be commented to
death is often the result of either a poor formal process,
which is typically document-driven rather than results-
driven, or bad personal experience — “Yeah, I
used to have to maintain this comment-free
spaghetti nightmare. So if you’re asking me whether
you should write comments, my view is that
programmers who don’t write comments should be
sacked.”
The view that code should always be comment-
free is sometimes derived from a notion of program
purity, so that code should be unsullied by anything
that the compiler does not use.The (worthy) ideal
is that code should be self-documenting. In other
cases, the ideal is one of laziness, a political stance
based on some notion of individual programmer
liberty, or both.
Inevitably, code and comments in the former style
fan the flames of support for the latter style, and vice-
versa.The third way on this is that code should indeed
be free of most of the kinds of comment that
satisfy the “any comment is a good comment”
crowd. A constructive approach to making code self-
documenting should be used rather than a polemical
only-good-comment-is-a-dead-comment.
Commenting should be minimal. However,
minimalism is not the same as nihilism. Code
should be made self-documenting not so much by
the omission of comments but by the adoption of
practices that make intent clear and code brief.
Labouring the point and using verbose coding
practices do not make code clearer, just laboured
and verbose. Most comments then become surplus
to requirements (functional requirements, operational
requirements or developmental requirements [1]
).
Once this more minimalist approach based on
communication is employed, comments can then
fill the gap between what can be and is said by the
code and the intent and model the programmer is
trying to communicate to the reader. Adopt this
approach and the role of comments then becomes
clear, as does their value.
Mostly useless
A comment that is wrong is by definition lying
to the reader. I don’t think that it would be too
q Comments are a form of code that is
not really code,so they are not subject
to the same rigorous practice as
executable or declarative code.
q Comments should be about
communication,not bureaucracy or
storytelling.
q Comments that get in the way,
because they are either wrong or
useless,are not harmless and should
be removed.
FACTS AT A GLANCE
PROGRAMMER’S WORKSHOP
Comments are in theory supposed to be a good thing, but in practice they are
often either abused or unused. Kevlin Henney offers comment on comments
Prefer code to comments
42 APPLICATION DEVELOPMENT ADVISOR q www.appdevadvisor.co.uk
SEPTEMBER–OCTOBER 2003 43
contentious to say that such comments should be deleted
without further ado. Such summary execution takes care of a
great many comments that you may encounter when dealing
with old code.
Other comments seem less harmful because they are not
misdirecting the reader, but at the same time, they are not exactly
useful, while some that appear useful are useful for the wrong
reasons. A comment with no use is, by definition, useless.
Useless comments seem to fall into one of a few categories:
q Multiple copyright messages or some other repeated legalese
and admin: One of these per file is both sensible and quite
enough; one per method is ridiculous. And given that the one
occurrence in a file is perfunctory, dull and often quite
long, there is a good case to be made for putting it at the end
of the source file, where it can be easily ignored, rather
than at its head, where it becomes the first thing you see when
you open the file.
q Comments that include version information: This is a job
best left to, and information best left in, the version control
system. If you are following a highly iterative development
style, you will find that such comments rapidly come to
dominate the source file. Sometimes comments can be
revealing, but embarrassingly so: I recall a collection of
source files that had “amended to allow compilation” as their
first version change. However, if your house rules feel the need
to mandate such versioning fluff in the source code, see if you
can place it at the end of the file out of harm’s way.
q Comments that describe the intent of a method in its
implementation: The intent of a method is best described in
its name and in any comment outside its implementation that
presents the method to the outside world, e.g. a sketch of its
contract [2]
.
q Comments that describe the implementation of a method along
with its intent: Does this mean that the external comment will
be updated every time the implementation of the method is
changed, whilst leaving the intent intact? Not in my
experience.
q Comments that parrot the code: Assume that the reader can
read the language you are writing. If they cannot, your
comments will be of minimal use unless they include a
guide to the language and its idioms (and no, that is not a
suggestion, although I have heard of it being done). A
comment that documents a method as taking three arguments
is a waste of space: that fact is obvious from the fact that its
argument list has three arguments, or that fact is clearly not
a fact if the method actually takes four. Likewise, documenting
the type and name of each argument is a good way of
repeating what is already in the code, but without the
guarantee of correctness. A comment that tells you that an
if statement on equality between two variables is comparing
two variables for equality is similarly unhelpful.
q Comments that tell you what someone has done: At best this is
gossip — “Joe added the following five lines” — and at worst
it falls rapidly out of date — “Joe added the following five
lines” ahead of ten lines of code... so which five did he
write and which mystery individual wrote the other five?
q Comments that tell you what to do: As generated by various
tools, TO DO comments suggest that there is something to be
done. This is fine if there is something to be done. However,
if you leave the comment in the code it means that it’s not
finished. When done, delete. In fact, even changing the
comment to DONE might be preferable to leaving it as TO DO!
Some programmers feel that they can’t touch the comment
because it was authored by an automatic code generator. Given
the quality of most automatically generated code, I don’t
understand the source of such reverence.
q Comments that describe what a piece of complex code does:
Sometimes such comments can prove useful, but more
often than not, they are an indication that something needs
to be re-factored and simplified. Such comments are glossing
over something that should be fixed. For instance, if a
method seems long and winding, don’t comment it: split it
up and make it shorter. Divide and conquer worked for Julius
Caesar and Tony Hoare; it also works a treat when you are
wondering what to re-factor and why.
q Commented-out code: The version control system is there to
act as the archivist and historian of your system. Commented-
out code does nothing, therefore it’s not really code, therefore
it will make no functional or operational difference if you
delete it, but the developmental difference will be an
improvement in readability and the removal of any lingering
doubts in the reader’s mind.
Heavy commenting often includes many of these kinds of
comments, and I suspect that some of it comes from programmers
who were not fully comfortable with the code. For some code
the sentiment is understandable, but think for a moment:
programmers who do not understand the code will invariably
describe it incorrectly, so how good will their comments be? Pouring
petrol onto a fire will not put it out.
In conclusion
Like gold, comments are valuable only when they are not
found under every rock or on every surface, but at the same time,
their existence must not be an impossibility. If comments flow
as freely as air they are worthless, acting as speed bumps to
comprehension rather than green lights. Prefer less to more, but
not necessarily none [3]
:
In other words, it’s not just a case of prefer good code to bad
comments: prefer good code to good comments. This
recommendation is an easy one to put into practice: read your
comments and if they give you news not trivia keep them, otherwise
reach for Del boy.
If you want to know what is happening, look at the code. If
you want to know why, then the gap between what can be read
from the code and what you need to know is what offers space
for documentation. Some of this may be in the form of
comments. s
References
1. Kevlin Henney, “Inside requirements”, Application
Development Advisor, May 2003.
2. Kevlin Henney, “Sorted”, Application Development
Advisor, July 2003.
3. Kevlin Henney, “The rest of the best”, Application
Development Advisor, June 2002.
Kevlin Henney is an independent software development consultant
and trainer. He can be reached at http://www.curbralan.com.
PROGRAMMER’S WORKSHOP

Más contenido relacionado

La actualidad más candente

OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ Ganesh Samarthyam
 
Solid OO & Clean Coding is essential to successful Agile development
Solid OO & Clean Coding is essential to successful Agile developmentSolid OO & Clean Coding is essential to successful Agile development
Solid OO & Clean Coding is essential to successful Agile developmentSimon Gould
 
Best Practices in Software Development
Best Practices in Software DevelopmentBest Practices in Software Development
Best Practices in Software DevelopmentAndré Pitombeira
 
Measuring Code Quality in WTF/min.
Measuring Code Quality in WTF/min. Measuring Code Quality in WTF/min.
Measuring Code Quality in WTF/min. David Gómez García
 
Refactoring Applications using SOLID Principles
Refactoring Applications using SOLID PrinciplesRefactoring Applications using SOLID Principles
Refactoring Applications using SOLID PrinciplesSteven Smith
 
Something for Nothing
Something for NothingSomething for Nothing
Something for NothingKevlin Henney
 
2015.01.09 - Writing Modern Applications for Mobile and Web
2015.01.09 - Writing Modern Applications for Mobile and Web2015.01.09 - Writing Modern Applications for Mobile and Web
2015.01.09 - Writing Modern Applications for Mobile and WebMarco Parenzan
 
Software Design Principles and Best Practices - Satyajit Dey
Software Design Principles and Best Practices - Satyajit DeySoftware Design Principles and Best Practices - Satyajit Dey
Software Design Principles and Best Practices - Satyajit DeyCefalo
 
WordCamp US: Clean Code
WordCamp US: Clean CodeWordCamp US: Clean Code
WordCamp US: Clean Codemtoppa
 
Writing High Quality Code in C#
Writing High Quality Code in C#Writing High Quality Code in C#
Writing High Quality Code in C#Svetlin Nakov
 
TDD Walkthrough - Encryption
TDD Walkthrough - EncryptionTDD Walkthrough - Encryption
TDD Walkthrough - EncryptionPeterKha2
 
Design poo my_jug_en_ppt
Design poo my_jug_en_pptDesign poo my_jug_en_ppt
Design poo my_jug_en_pptagnes_crepet
 
Design for Testability
Design for Testability Design for Testability
Design for Testability Pawel Kalbrun
 
Systematic error management - we ported rudder to zio
Systematic error management - we ported rudder to zioSystematic error management - we ported rudder to zio
Systematic error management - we ported rudder to ziofanf42
 

La actualidad más candente (20)

SAD10 - Refactoring
SAD10 - RefactoringSAD10 - Refactoring
SAD10 - Refactoring
 
OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++
 
Solid OO & Clean Coding is essential to successful Agile development
Solid OO & Clean Coding is essential to successful Agile developmentSolid OO & Clean Coding is essential to successful Agile development
Solid OO & Clean Coding is essential to successful Agile development
 
Best Practices in Software Development
Best Practices in Software DevelopmentBest Practices in Software Development
Best Practices in Software Development
 
Measuring Code Quality in WTF/min.
Measuring Code Quality in WTF/min. Measuring Code Quality in WTF/min.
Measuring Code Quality in WTF/min.
 
Getting Started With Testing
Getting Started With TestingGetting Started With Testing
Getting Started With Testing
 
Clean Code V2
Clean Code V2Clean Code V2
Clean Code V2
 
Refactoring Applications using SOLID Principles
Refactoring Applications using SOLID PrinciplesRefactoring Applications using SOLID Principles
Refactoring Applications using SOLID Principles
 
Something for Nothing
Something for NothingSomething for Nothing
Something for Nothing
 
Thoughtful Software Design
Thoughtful Software DesignThoughtful Software Design
Thoughtful Software Design
 
2015.01.09 - Writing Modern Applications for Mobile and Web
2015.01.09 - Writing Modern Applications for Mobile and Web2015.01.09 - Writing Modern Applications for Mobile and Web
2015.01.09 - Writing Modern Applications for Mobile and Web
 
Software Design Principles and Best Practices - Satyajit Dey
Software Design Principles and Best Practices - Satyajit DeySoftware Design Principles and Best Practices - Satyajit Dey
Software Design Principles and Best Practices - Satyajit Dey
 
Clean code-v2.2
Clean code-v2.2Clean code-v2.2
Clean code-v2.2
 
WordCamp US: Clean Code
WordCamp US: Clean CodeWordCamp US: Clean Code
WordCamp US: Clean Code
 
Writing High Quality Code in C#
Writing High Quality Code in C#Writing High Quality Code in C#
Writing High Quality Code in C#
 
BDD Primer
BDD PrimerBDD Primer
BDD Primer
 
TDD Walkthrough - Encryption
TDD Walkthrough - EncryptionTDD Walkthrough - Encryption
TDD Walkthrough - Encryption
 
Design poo my_jug_en_ppt
Design poo my_jug_en_pptDesign poo my_jug_en_ppt
Design poo my_jug_en_ppt
 
Design for Testability
Design for Testability Design for Testability
Design for Testability
 
Systematic error management - we ported rudder to zio
Systematic error management - we ported rudder to zioSystematic error management - we ported rudder to zio
Systematic error management - we ported rudder to zio
 

Destacado

5M Your Inspiring Training Partner
5M Your Inspiring Training Partner5M Your Inspiring Training Partner
5M Your Inspiring Training Partner5mispvt company
 
Density functional theory calculations on Ruthenium polypyridyl complexes inc...
Density functional theory calculations on Ruthenium polypyridyl complexes inc...Density functional theory calculations on Ruthenium polypyridyl complexes inc...
Density functional theory calculations on Ruthenium polypyridyl complexes inc...baoilleach
 
HAPPYWEEK 192 - 2016.10.31.
HAPPYWEEK 192 - 2016.10.31.HAPPYWEEK 192 - 2016.10.31.
HAPPYWEEK 192 - 2016.10.31.Jiří Černák
 
L&D in a Social World
L&D in a Social WorldL&D in a Social World
L&D in a Social WorldJane Hart
 
btc-e chat history
btc-e chat historybtc-e chat history
btc-e chat historyboxbandit
 
某球侠的奥林匹克——羽毛球现场观球记
某球侠的奥林匹克——羽毛球现场观球记某球侠的奥林匹克——羽毛球现场观球记
某球侠的奥林匹克——羽毛球现场观球记qyqing
 
Contaminacion del suelo
Contaminacion del sueloContaminacion del suelo
Contaminacion del suelolianeclucena
 
Unit 1 Nouns
Unit 1 NounsUnit 1 Nouns
Unit 1 NounsNixie05
 
Fatih projesi
Fatih projesiFatih projesi
Fatih projesiFLakyLive
 
ロボットによるサッカー対決
ロボットによるサッカー対決ロボットによるサッカー対決
ロボットによるサッカー対決stucon
 
Diapositivas de dhtic
Diapositivas de dhticDiapositivas de dhtic
Diapositivas de dhticYatziil MnDz
 
How to Manage Testing in Dynamic World
How to Manage Testing in Dynamic WorldHow to Manage Testing in Dynamic World
How to Manage Testing in Dynamic WorldAndrii Dzynia
 
La préfecture interdit toute manifestation aux abords du bar identitaire, samedi
La préfecture interdit toute manifestation aux abords du bar identitaire, samediLa préfecture interdit toute manifestation aux abords du bar identitaire, samedi
La préfecture interdit toute manifestation aux abords du bar identitaire, samediJean-michel Neugate
 
GOOGLE AND TATA || EKUTIR JOIN HANDS TO MAKE INDIA RICH
GOOGLE AND TATA  || EKUTIR  JOIN HANDS TO MAKE INDIA RICHGOOGLE AND TATA  || EKUTIR  JOIN HANDS TO MAKE INDIA RICH
GOOGLE AND TATA || EKUTIR JOIN HANDS TO MAKE INDIA RICHRubalSingh
 

Destacado (20)

5M Your Inspiring Training Partner
5M Your Inspiring Training Partner5M Your Inspiring Training Partner
5M Your Inspiring Training Partner
 
Density functional theory calculations on Ruthenium polypyridyl complexes inc...
Density functional theory calculations on Ruthenium polypyridyl complexes inc...Density functional theory calculations on Ruthenium polypyridyl complexes inc...
Density functional theory calculations on Ruthenium polypyridyl complexes inc...
 
sombreros vueltiaos
sombreros vueltiaos sombreros vueltiaos
sombreros vueltiaos
 
HAPPYWEEK 192 - 2016.10.31.
HAPPYWEEK 192 - 2016.10.31.HAPPYWEEK 192 - 2016.10.31.
HAPPYWEEK 192 - 2016.10.31.
 
L&D in a Social World
L&D in a Social WorldL&D in a Social World
L&D in a Social World
 
btc-e chat history
btc-e chat historybtc-e chat history
btc-e chat history
 
某球侠的奥林匹克——羽毛球现场观球记
某球侠的奥林匹克——羽毛球现场观球记某球侠的奥林匹克——羽毛球现场观球记
某球侠的奥林匹克——羽毛球现场观球记
 
Contaminacion del suelo
Contaminacion del sueloContaminacion del suelo
Contaminacion del suelo
 
Unit 1 Nouns
Unit 1 NounsUnit 1 Nouns
Unit 1 Nouns
 
Fatih projesi
Fatih projesiFatih projesi
Fatih projesi
 
ロボットによるサッカー対決
ロボットによるサッカー対決ロボットによるサッカー対決
ロボットによるサッカー対決
 
Daljeet CV (2)
Daljeet CV (2)Daljeet CV (2)
Daljeet CV (2)
 
Danh sach so do
Danh sach so doDanh sach so do
Danh sach so do
 
ARC/NHMRC Grant Compliance @ UWS
ARC/NHMRC Grant Compliance @ UWSARC/NHMRC Grant Compliance @ UWS
ARC/NHMRC Grant Compliance @ UWS
 
Diapositivas de dhtic
Diapositivas de dhticDiapositivas de dhtic
Diapositivas de dhtic
 
How to Manage Testing in Dynamic World
How to Manage Testing in Dynamic WorldHow to Manage Testing in Dynamic World
How to Manage Testing in Dynamic World
 
Wiggins 2013 05-29
Wiggins 2013 05-29Wiggins 2013 05-29
Wiggins 2013 05-29
 
La préfecture interdit toute manifestation aux abords du bar identitaire, samedi
La préfecture interdit toute manifestation aux abords du bar identitaire, samediLa préfecture interdit toute manifestation aux abords du bar identitaire, samedi
La préfecture interdit toute manifestation aux abords du bar identitaire, samedi
 
Green buildings in qatar
Green buildings in qatarGreen buildings in qatar
Green buildings in qatar
 
GOOGLE AND TATA || EKUTIR JOIN HANDS TO MAKE INDIA RICH
GOOGLE AND TATA  || EKUTIR  JOIN HANDS TO MAKE INDIA RICHGOOGLE AND TATA  || EKUTIR  JOIN HANDS TO MAKE INDIA RICH
GOOGLE AND TATA || EKUTIR JOIN HANDS TO MAKE INDIA RICH
 

Similar a Prefer Code to Comments

Code review best practice
Code review best practiceCode review best practice
Code review best practiceOren Digmi
 
Tips to Comment the Code
Tips to Comment the CodeTips to Comment the Code
Tips to Comment the CodeSoftheme
 
API Workshop: Deep dive into code samples
API Workshop: Deep dive into code samplesAPI Workshop: Deep dive into code samples
API Workshop: Deep dive into code samplesTom Johnson
 
On Readability of Code
On Readability of CodeOn Readability of Code
On Readability of CodeArun Saha
 
10 Faulty Behaviors of Code Review - Developer Summit Istanbul 2018
10 Faulty Behaviors of Code Review - Developer Summit Istanbul 201810 Faulty Behaviors of Code Review - Developer Summit Istanbul 2018
10 Faulty Behaviors of Code Review - Developer Summit Istanbul 2018Lemi Orhan Ergin
 
WordCamp Nashville: Clean Code for WordPress
WordCamp Nashville: Clean Code for WordPressWordCamp Nashville: Clean Code for WordPress
WordCamp Nashville: Clean Code for WordPressmtoppa
 
WordCamp Pune 2017- WordPress Coding standards
WordCamp Pune 2017- WordPress Coding standardsWordCamp Pune 2017- WordPress Coding standards
WordCamp Pune 2017- WordPress Coding standardsSwapnil Patil
 
Writing code samples for API/SDK documentation
Writing code samples for API/SDK documentationWriting code samples for API/SDK documentation
Writing code samples for API/SDK documentationTom Johnson
 
Documenting code yapceu2016
Documenting code yapceu2016Documenting code yapceu2016
Documenting code yapceu2016Søren Lund
 
Scottish Ruby Conference 2014
Scottish Ruby Conference  2014Scottish Ruby Conference  2014
Scottish Ruby Conference 2014michaelag1971
 
Clean Code Software Engineering
Clean Code Software Engineering Clean Code Software Engineering
Clean Code Software Engineering Inocentshuja Ahmad
 
60 terrible tips for a C++ developer
60 terrible tips for a C++ developer60 terrible tips for a C++ developer
60 terrible tips for a C++ developerAndrey Karpov
 
It is difficult
It is difficultIt is difficult
It is difficultPVS-Studio
 
10 Code Anti-Patterns to Avoid in Software Development.pdf
10 Code Anti-Patterns to Avoid in Software Development.pdf10 Code Anti-Patterns to Avoid in Software Development.pdf
10 Code Anti-Patterns to Avoid in Software Development.pdfAhmed Salama
 
Cinci ug-january2011-anti-patterns
Cinci ug-january2011-anti-patternsCinci ug-january2011-anti-patterns
Cinci ug-january2011-anti-patternsSteven Smith
 
Documenting Code - Patterns and Anti-patterns - NLPW 2016
Documenting Code - Patterns and Anti-patterns - NLPW 2016Documenting Code - Patterns and Anti-patterns - NLPW 2016
Documenting Code - Patterns and Anti-patterns - NLPW 2016Søren Lund
 
Writing code for people
Writing code for peopleWriting code for people
Writing code for peopleAlexey Ivanov
 

Similar a Prefer Code to Comments (20)

Code comment-training
Code comment-trainingCode comment-training
Code comment-training
 
Code review best practice
Code review best practiceCode review best practice
Code review best practice
 
Tips to Comment the Code
Tips to Comment the CodeTips to Comment the Code
Tips to Comment the Code
 
Put to the Test
Put to the TestPut to the Test
Put to the Test
 
API Workshop: Deep dive into code samples
API Workshop: Deep dive into code samplesAPI Workshop: Deep dive into code samples
API Workshop: Deep dive into code samples
 
On Readability of Code
On Readability of CodeOn Readability of Code
On Readability of Code
 
10 Faulty Behaviors of Code Review - Developer Summit Istanbul 2018
10 Faulty Behaviors of Code Review - Developer Summit Istanbul 201810 Faulty Behaviors of Code Review - Developer Summit Istanbul 2018
10 Faulty Behaviors of Code Review - Developer Summit Istanbul 2018
 
WordCamp Nashville: Clean Code for WordPress
WordCamp Nashville: Clean Code for WordPressWordCamp Nashville: Clean Code for WordPress
WordCamp Nashville: Clean Code for WordPress
 
WordCamp Pune 2017- WordPress Coding standards
WordCamp Pune 2017- WordPress Coding standardsWordCamp Pune 2017- WordPress Coding standards
WordCamp Pune 2017- WordPress Coding standards
 
Writing code samples for API/SDK documentation
Writing code samples for API/SDK documentationWriting code samples for API/SDK documentation
Writing code samples for API/SDK documentation
 
Documenting code yapceu2016
Documenting code yapceu2016Documenting code yapceu2016
Documenting code yapceu2016
 
Scottish Ruby Conference 2014
Scottish Ruby Conference  2014Scottish Ruby Conference  2014
Scottish Ruby Conference 2014
 
Clean Code Software Engineering
Clean Code Software Engineering Clean Code Software Engineering
Clean Code Software Engineering
 
60 terrible tips for a C++ developer
60 terrible tips for a C++ developer60 terrible tips for a C++ developer
60 terrible tips for a C++ developer
 
It is difficult
It is difficultIt is difficult
It is difficult
 
10 Code Anti-Patterns to Avoid in Software Development.pdf
10 Code Anti-Patterns to Avoid in Software Development.pdf10 Code Anti-Patterns to Avoid in Software Development.pdf
10 Code Anti-Patterns to Avoid in Software Development.pdf
 
Cinci ug-january2011-anti-patterns
Cinci ug-january2011-anti-patternsCinci ug-january2011-anti-patterns
Cinci ug-january2011-anti-patterns
 
Documenting Code - Patterns and Anti-patterns - NLPW 2016
Documenting Code - Patterns and Anti-patterns - NLPW 2016Documenting Code - Patterns and Anti-patterns - NLPW 2016
Documenting Code - Patterns and Anti-patterns - NLPW 2016
 
Code reviews
Code reviewsCode reviews
Code reviews
 
Writing code for people
Writing code for peopleWriting code for people
Writing code for people
 

Más de Kevlin Henney

The Case for Technical Excellence
The Case for Technical ExcellenceThe Case for Technical Excellence
The Case for Technical ExcellenceKevlin Henney
 
Empirical Development
Empirical DevelopmentEmpirical Development
Empirical DevelopmentKevlin Henney
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that LetterKevlin Henney
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that LetterKevlin Henney
 
Solid Deconstruction
Solid DeconstructionSolid Deconstruction
Solid DeconstructionKevlin Henney
 
Procedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went AwayProcedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went AwayKevlin Henney
 
Structure and Interpretation of Test Cases
Structure and Interpretation of Test CasesStructure and Interpretation of Test Cases
Structure and Interpretation of Test CasesKevlin Henney
 
Refactoring to Immutability
Refactoring to ImmutabilityRefactoring to Immutability
Refactoring to ImmutabilityKevlin Henney
 
Turning Development Outside-In
Turning Development Outside-InTurning Development Outside-In
Turning Development Outside-InKevlin Henney
 
Giving Code a Good Name
Giving Code a Good NameGiving Code a Good Name
Giving Code a Good NameKevlin Henney
 
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...Kevlin Henney
 
Thinking Outside the Synchronisation Quadrant
Thinking Outside the Synchronisation QuadrantThinking Outside the Synchronisation Quadrant
Thinking Outside the Synchronisation QuadrantKevlin Henney
 

Más de Kevlin Henney (20)

Program with GUTs
Program with GUTsProgram with GUTs
Program with GUTs
 
The Case for Technical Excellence
The Case for Technical ExcellenceThe Case for Technical Excellence
The Case for Technical Excellence
 
Empirical Development
Empirical DevelopmentEmpirical Development
Empirical Development
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that Letter
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that Letter
 
Solid Deconstruction
Solid DeconstructionSolid Deconstruction
Solid Deconstruction
 
Get Kata
Get KataGet Kata
Get Kata
 
Procedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went AwayProcedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went Away
 
Structure and Interpretation of Test Cases
Structure and Interpretation of Test CasesStructure and Interpretation of Test Cases
Structure and Interpretation of Test Cases
 
Agility ≠ Speed
Agility ≠ SpeedAgility ≠ Speed
Agility ≠ Speed
 
Refactoring to Immutability
Refactoring to ImmutabilityRefactoring to Immutability
Refactoring to Immutability
 
Old Is the New New
Old Is the New NewOld Is the New New
Old Is the New New
 
Turning Development Outside-In
Turning Development Outside-InTurning Development Outside-In
Turning Development Outside-In
 
Giving Code a Good Name
Giving Code a Good NameGiving Code a Good Name
Giving Code a Good Name
 
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
 
Thinking Outside the Synchronisation Quadrant
Thinking Outside the Synchronisation QuadrantThinking Outside the Synchronisation Quadrant
Thinking Outside the Synchronisation Quadrant
 
Code as Risk
Code as RiskCode as Risk
Code as Risk
 
Software Is Details
Software Is DetailsSoftware Is Details
Software Is Details
 
Game of Sprints
Game of SprintsGame of Sprints
Game of Sprints
 
Good Code
Good CodeGood Code
Good Code
 

Último

A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogueitservices996
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slidesvaideheekore1
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptxVinzoCenzo
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolsosttopstonverter
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxRTS corp
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...OnePlan Solutions
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesVictoriaMetrics
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonApplitools
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 

Último (20)

A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogue
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slides
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptx
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration tools
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 Updates
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 

Prefer Code to Comments

  • 1. Y OUR CODE READING SPEED IS AFFECTED by many factors, some of which depend on you, some of which depend on the code. For instance, your ability to parse and grasp code will be lower in the post-lunch siesta part of the afternoon than during the up-’n’-at-’em, caffeine-injected start of the day. You can grasp code more rapidly and accurately when it is based on familiar patterns rather than someone else’s programming idiolect. Reading through long- winded or poorly constructed logic and control flow is more akin to wading through molasses than cutting through butter. However, super-clever code trickery or cryptic conventions keep you guessing. And then there are comments. Comments should improve the readability of the code, but so often, the opposite is true. As with so many shoulds in life, it takes more than just saying it to get it right. Comments are an odd form of code: they are code that is not code. They are bound by a formal syntax but, with the exception of particular annotations for certain tools, comments are not read by compilers. Hmm, for that matter, they are not really read by programmers. Goldilocks and the three programmers When it comes to estimating the value of comments, there are three basic schools of thought: any comment is a good comment; any comment is a bad comment; only comments that communicate are good, all the rest are bad. This is a bit like Goldilocks with her porridge pilfering: too hot, too cold, just right. The view that all code should be commented to death is often the result of either a poor formal process, which is typically document-driven rather than results- driven, or bad personal experience — “Yeah, I used to have to maintain this comment-free spaghetti nightmare. So if you’re asking me whether you should write comments, my view is that programmers who don’t write comments should be sacked.” The view that code should always be comment- free is sometimes derived from a notion of program purity, so that code should be unsullied by anything that the compiler does not use.The (worthy) ideal is that code should be self-documenting. In other cases, the ideal is one of laziness, a political stance based on some notion of individual programmer liberty, or both. Inevitably, code and comments in the former style fan the flames of support for the latter style, and vice- versa.The third way on this is that code should indeed be free of most of the kinds of comment that satisfy the “any comment is a good comment” crowd. A constructive approach to making code self- documenting should be used rather than a polemical only-good-comment-is-a-dead-comment. Commenting should be minimal. However, minimalism is not the same as nihilism. Code should be made self-documenting not so much by the omission of comments but by the adoption of practices that make intent clear and code brief. Labouring the point and using verbose coding practices do not make code clearer, just laboured and verbose. Most comments then become surplus to requirements (functional requirements, operational requirements or developmental requirements [1] ). Once this more minimalist approach based on communication is employed, comments can then fill the gap between what can be and is said by the code and the intent and model the programmer is trying to communicate to the reader. Adopt this approach and the role of comments then becomes clear, as does their value. Mostly useless A comment that is wrong is by definition lying to the reader. I don’t think that it would be too q Comments are a form of code that is not really code,so they are not subject to the same rigorous practice as executable or declarative code. q Comments should be about communication,not bureaucracy or storytelling. q Comments that get in the way, because they are either wrong or useless,are not harmless and should be removed. FACTS AT A GLANCE PROGRAMMER’S WORKSHOP Comments are in theory supposed to be a good thing, but in practice they are often either abused or unused. Kevlin Henney offers comment on comments Prefer code to comments 42 APPLICATION DEVELOPMENT ADVISOR q www.appdevadvisor.co.uk
  • 2. SEPTEMBER–OCTOBER 2003 43 contentious to say that such comments should be deleted without further ado. Such summary execution takes care of a great many comments that you may encounter when dealing with old code. Other comments seem less harmful because they are not misdirecting the reader, but at the same time, they are not exactly useful, while some that appear useful are useful for the wrong reasons. A comment with no use is, by definition, useless. Useless comments seem to fall into one of a few categories: q Multiple copyright messages or some other repeated legalese and admin: One of these per file is both sensible and quite enough; one per method is ridiculous. And given that the one occurrence in a file is perfunctory, dull and often quite long, there is a good case to be made for putting it at the end of the source file, where it can be easily ignored, rather than at its head, where it becomes the first thing you see when you open the file. q Comments that include version information: This is a job best left to, and information best left in, the version control system. If you are following a highly iterative development style, you will find that such comments rapidly come to dominate the source file. Sometimes comments can be revealing, but embarrassingly so: I recall a collection of source files that had “amended to allow compilation” as their first version change. However, if your house rules feel the need to mandate such versioning fluff in the source code, see if you can place it at the end of the file out of harm’s way. q Comments that describe the intent of a method in its implementation: The intent of a method is best described in its name and in any comment outside its implementation that presents the method to the outside world, e.g. a sketch of its contract [2] . q Comments that describe the implementation of a method along with its intent: Does this mean that the external comment will be updated every time the implementation of the method is changed, whilst leaving the intent intact? Not in my experience. q Comments that parrot the code: Assume that the reader can read the language you are writing. If they cannot, your comments will be of minimal use unless they include a guide to the language and its idioms (and no, that is not a suggestion, although I have heard of it being done). A comment that documents a method as taking three arguments is a waste of space: that fact is obvious from the fact that its argument list has three arguments, or that fact is clearly not a fact if the method actually takes four. Likewise, documenting the type and name of each argument is a good way of repeating what is already in the code, but without the guarantee of correctness. A comment that tells you that an if statement on equality between two variables is comparing two variables for equality is similarly unhelpful. q Comments that tell you what someone has done: At best this is gossip — “Joe added the following five lines” — and at worst it falls rapidly out of date — “Joe added the following five lines” ahead of ten lines of code... so which five did he write and which mystery individual wrote the other five? q Comments that tell you what to do: As generated by various tools, TO DO comments suggest that there is something to be done. This is fine if there is something to be done. However, if you leave the comment in the code it means that it’s not finished. When done, delete. In fact, even changing the comment to DONE might be preferable to leaving it as TO DO! Some programmers feel that they can’t touch the comment because it was authored by an automatic code generator. Given the quality of most automatically generated code, I don’t understand the source of such reverence. q Comments that describe what a piece of complex code does: Sometimes such comments can prove useful, but more often than not, they are an indication that something needs to be re-factored and simplified. Such comments are glossing over something that should be fixed. For instance, if a method seems long and winding, don’t comment it: split it up and make it shorter. Divide and conquer worked for Julius Caesar and Tony Hoare; it also works a treat when you are wondering what to re-factor and why. q Commented-out code: The version control system is there to act as the archivist and historian of your system. Commented- out code does nothing, therefore it’s not really code, therefore it will make no functional or operational difference if you delete it, but the developmental difference will be an improvement in readability and the removal of any lingering doubts in the reader’s mind. Heavy commenting often includes many of these kinds of comments, and I suspect that some of it comes from programmers who were not fully comfortable with the code. For some code the sentiment is understandable, but think for a moment: programmers who do not understand the code will invariably describe it incorrectly, so how good will their comments be? Pouring petrol onto a fire will not put it out. In conclusion Like gold, comments are valuable only when they are not found under every rock or on every surface, but at the same time, their existence must not be an impossibility. If comments flow as freely as air they are worthless, acting as speed bumps to comprehension rather than green lights. Prefer less to more, but not necessarily none [3] : In other words, it’s not just a case of prefer good code to bad comments: prefer good code to good comments. This recommendation is an easy one to put into practice: read your comments and if they give you news not trivia keep them, otherwise reach for Del boy. If you want to know what is happening, look at the code. If you want to know why, then the gap between what can be read from the code and what you need to know is what offers space for documentation. Some of this may be in the form of comments. s References 1. Kevlin Henney, “Inside requirements”, Application Development Advisor, May 2003. 2. Kevlin Henney, “Sorted”, Application Development Advisor, July 2003. 3. Kevlin Henney, “The rest of the best”, Application Development Advisor, June 2002. Kevlin Henney is an independent software development consultant and trainer. He can be reached at http://www.curbralan.com. PROGRAMMER’S WORKSHOP