SlideShare a Scribd company logo
@PeterHilton
http://hilton.org.uk/
How to write
good comments
# Single-line comments in:
# BASH, CoffeeScript, Perl, PHP, Python, Ruby, YAML,
// C, C++, C#, F#, Java, JavaScript, PHP,
-- Haskell, SQL,
; Assembler, Common Lisp, Emacs Lisp, Logo, Scheme,
% Erlang, PostScript, Prolog, TeX,
' Visual basic,
C FORTRAN,
rem BASIC
=begin
Multi-line comments in:
Ruby,
=end
/*
C, C++, Java, JavaScript, PHP
*/
<!--
HTML, XML
-->
###
CoffeeScript
###
http://rigaux.org/language-study/syntax-across-languages.html#VrsCmmnt
Code comments
What are comments?
Comments are annotations in source code, written
for programmers who maintain the code.
Comments are the only feature common to all*
programming languages.
Comments are amazingly useful, mainly because
we spend more time reading code than writing it.
* general purpose languages 5@PeterHilton •
What are comments for?
‘Comments are usually added with the purpose of
making the source code easier to understand, …’
‘How best to make use of comments is subject to
dispute; different commentators have offered
varied and sometimes opposing viewpoints.’
http://en.wikipedia.org/wiki/Comment_(computer_programming) 6@PeterHilton •
Who are comments for
Comments are, in the first instance, for yourself.
This includes your future self, who will thank you
for learning to write good comments.
Your colleagues will also thank you, especially if
you’re better at it than them, and write theirs too.
X@PeterHilton •
What is the problem?
X@PeterHilton •
Writing comments is harder than 

writing or coding
(because it’s both)
Programmers* don’t like writing
(or talking about writing comments)
* most programmers
Kinds of useful
comments
Existential
angst kitten
wants to
know why?
bontempscharly / CC BY 2.0
// Returns zero for dead kittens (not cute).
// Throws IllegalArgumentException for cats
// that are too old to be kittens.
def estimateCuteness(kitten: Kitten): Int = ???
case class Kitten(
photo: URL,
cutenessScore: Int,
age: Duration)
// Photo of a kitten to console
// a trader after a loss, with
// cuteness proportional to the
// magnitude of the loss.
// Returns a cuteness score estimate for
// non-dead kittens less than one year old.
class Kitten
attr_accessor :photoUrl
attr_accessor :cutenessScore
attr_accessor :age
def initialize photoUrl, cutenessScore, age
@photoUrl = photoUrl
@cutenessScore = cutenessScore
@age = age
end
end
# Photo of a kitten to console a trader after a loss, with
# cuteness proportional to the magnitude of the loss.
Explain why the code exists
Good comments answer the ‘why?’ questions in a
way that good code cannot.
Code cannot explain its own existence.
When should I use this code?
What are the alternatives to this code?
10@PeterHilton •
def estimateCuteness kitten
# TODO
end
# Returns an estimated cuteness score for a kitten.
# Returns an estimated cuteness score for a kitten.
# * Returns zero for dead kittens (not cute).
# * Raises an exception for cats that are too old to be kittens.
Pre-conditions, restrictions and limitations
Explain pre-conditions, needed for working code,
e.g. valid values
Explain restrictions - when the code won’t work,
e.g. values that are not supported
Tell me when I shouldn’t use this code
Explain why pre-conditions and limitations apply.
12@PeterHilton •
Comments are the introduction
Lengthy code needs an introduction, just like a
book or long document, to explain:
purpose - what it’s for
scope - who it’s for and when it applies
summary - what it’s about
http://hilton.org.uk/blog/comments-are-the-introduction 14@PeterHilton •
Explain implementation choices
Why is that the right functionality?
Why is it implemented this way?
Why wasn’t it done the obvious way?
Exceptions to coding standards often require a
comment to say what’s going on.
15@PeterHilton •
/**
* Deprecated: Use a kitten instead
*/
case class ConsolationPuppy(photo: URL,
cuteness: Score, age: Duration)
/**
* We use kittens instead of puppies,
* which turn out to be less cute.
*/
case class ConsolationKitten(photo: URL,
cuteness: Score, age: Duration)
Comment the code that isn’t there
Sometimes, you need to talk about code that isn’t
there any more:
Failed approaches
Code before optimisation
Functionality that became superfluous
X@PeterHilton •
Concrete API usage examples
Using an API can be difficult without having usage
examples.
This shouldn’t apply to application code, because
there should always be usages
X@PeterHilton •
Compensate for different levels of fluency in the
team
Write for your audience - including the future team,
and especially on a multi-disciplinary team
Don’t mix jargon from different areas - from both
problem domain and solution domain
New team members shouldn’t need to understand
everything to read anything
16@PeterHilton •
Summary of useful comments
1. Purpose
2. Scope introduction
3. Summary
4. Limitations
5. Alternatives
6. Examples
7. Explanations for new team members
http://hilton.org.uk/blog/3-kinds-of-good-comments 17@PeterHilton •
}
How to write good
comments
No comments at all is
giving up.
You can do better than
that.
@PeterHilton • X
Documentation comments
Comments can document code’s public interface -
how other programmers will use the code.
Write a one-sentence comment for every:
class and public method (or function)
Use consistent grammar for documentation
comments, e.g. ‘Returns…’
X@PeterHilton •
Discover which comments are hard to write,
and why
If a comment is easy to write, then that code
probably doesn’t need a comment (right now).
How to test code for maintainability:
1. Write a one-sentence comment,

for every class and method (or function).
2. (there is no 2)
19@PeterHilton •
Rewriting comments
It is unreasonable to expect to write a comment
once and never have to edit it.
Comments require review, rewrites and refactoring,
just like code.
Include comments in code review.
Comments are not separate from code.
20@PeterHilton •
Deleting comments
Improving code includes deleting comments, 

as well as deleting code.
Delete the comments you don’t need, to 

leave more room for the ones you do need.
Refactor the code, then repeat.
http://hilton.org.uk/blog/how-to-comment-code 21@PeterHilton •
‘A common fallacy is to assume authors of
incomprehensible code will somehow be able to
express themselves lucidly and clearly in
comments.’
@KevlinHenney
X@PeterHilton •
Acknowledge that writing (comments) is a
specialist skill
On a cross-functional development team, not
everyone is good at visual design.
The same goes for writing about code.
Work out who is a better writer.
Get help with writing comments.
X@PeterHilton •
Bad comments
Bad code and comments
Comments sometimes compensate for bad code.
Bad code is usually benefits from comments.
Improving bad code usually makes some comments
unnecessary.
(But don’t remove useful comments without
actually improving the code first.)
23@PeterHilton •
Refactoring to avoid the need for
comments
X@PeterHilton •
Better modelling and naming communicate
purpose a.k.a intention.
Domain-Driven Design is your friend
Avoid primitive types in APIs
Extracting and naming local expressions
(and encapsulating logic in functions)
makes code its own summary.
Adding tests
Tests can communicate requirements and
intention, and demonstrate using an API
… but not necessarily
Tests have a different primary purpose and are
separate from the code they test
… and might even be written first
X@PeterHilton •
Don’t write bad comments!
1. Don’t say what the code does

(because the code already says that)
2. Don’t explain bad code & awkward logic

(refactor the code to make it clear)
3. Don’t add too many comments

(it’s messy and they’ll get out of date)
4. Write unit tests instead
24@PeterHilton •
7 sins of bad comments
25@PeterHilton •
1. Errors in syntax or grammar
2. Out-of-date with respect to the code
3. Verbose, taking up too much space
4. Too numerous, adding clutter
5. Duplicating the code
6. Explaining awkward logic
7. Contradicting the code
http://hilton.org.uk/blog/7-ways-to-write-bad-comments
Refactoring to avoid the need for comments
Better modelling and naming communicate
purpose a.k.a intention.
Domain-Driven Design is your friend
Avoid primitive types in APIs
Extracting and naming local expressions
(and encapsulating logic in functions)
makes code its own summary. X@PeterHilton •
Adding tests
Tests can communicate requirements and
intention, and demonstrate using an API
… but not necessarily
Tests have a different primary purpose and are
separate from the code they test
… and might even be written first
X@PeterHilton •
Summary
Comments are hard
Not everyone is good at writing, and technical
writing is a specialism like user interface design.
Writing comments is harder than writing or coding
(because it includes both).
Programmers* don’t like writing, which includes
writing comments.
* some programmers 27@PeterHilton •
How to write good comments (summary)
1. Try to write good code first.
2. Write a one-sentence comment.
3. Refactor the code (make it easier to understand).
4. Delete unnecessary comments.
5. Rewrite bad comments

(all good writing requires rewriting)
6. Add detail where needed.
7. Do it for your future self. 28@PeterHilton •
When programming,
use the best language
for the job.
Sometimes, it’s English.
@PeterHilton • X
@PeterHilton
http://hilton.org.uk/

More Related Content

What's hot

Programming Fundamental Presentation
Programming Fundamental PresentationProgramming Fundamental Presentation
Programming Fundamental Presentation
fazli khaliq
 
Computer Language Translator
Computer Language TranslatorComputer Language Translator
Computer Language Translator
Ranjeet Kumar
 
Introduction to Technical Writing - Priti Gaikwad
Introduction to Technical Writing - Priti GaikwadIntroduction to Technical Writing - Priti Gaikwad
Introduction to Technical Writing - Priti Gaikwad
Priti Gaikwad
 
Introduction to Selection control structures in C++
Introduction to Selection control structures in C++ Introduction to Selection control structures in C++
Introduction to Selection control structures in C++
Neeru Mittal
 
Prgramming paradigms
Prgramming paradigmsPrgramming paradigms
Prgramming paradigms
Anirudh Chauhan
 
C basics 4 std11(GujBoard)
C basics 4 std11(GujBoard)C basics 4 std11(GujBoard)
C basics 4 std11(GujBoard)indrasir
 
Lecture 04 writing a memorandum
Lecture 04 writing a memorandumLecture 04 writing a memorandum
Lecture 04 writing a memorandum
Dynamic Research Centre & institute
 
FOUR DIFFERENT TYPES OF WRITING STYLES
FOUR DIFFERENT TYPES OF WRITING STYLESFOUR DIFFERENT TYPES OF WRITING STYLES
FOUR DIFFERENT TYPES OF WRITING STYLES
Mahmud Hasan Tanvir
 
The Linux Scheduler: a Decade of Wasted Cores
The Linux Scheduler: a Decade of Wasted CoresThe Linux Scheduler: a Decade of Wasted Cores
The Linux Scheduler: a Decade of Wasted Cores
yeokm1
 
Dictionary, encyclopedia and thesaurus
Dictionary, encyclopedia and thesaurusDictionary, encyclopedia and thesaurus
Dictionary, encyclopedia and thesaurus
Laura-Nozal
 
Essay structure
Essay structure Essay structure
Essay structure
lcslidepresentations
 
Control Flow Statements
Control Flow Statements Control Flow Statements
Control Flow Statements
Tarun Sharma
 
C++
C++C++
ReactJS presentation.pptx
ReactJS presentation.pptxReactJS presentation.pptx
ReactJS presentation.pptx
DivyanshGupta922023
 
Citing sources--a review
Citing sources--a reviewCiting sources--a review
Citing sources--a review
Shelli Seehusen
 
Unit 2 computer software
Unit 2 computer softwareUnit 2 computer software
Unit 2 computer software
Hardik Patel
 
How to execute a C program
How to execute a C  program How to execute a C  program
How to execute a C program
Leela Koneru
 

What's hot (20)

Programming Fundamental Presentation
Programming Fundamental PresentationProgramming Fundamental Presentation
Programming Fundamental Presentation
 
Computer Language Translator
Computer Language TranslatorComputer Language Translator
Computer Language Translator
 
Introduction to Technical Writing - Priti Gaikwad
Introduction to Technical Writing - Priti GaikwadIntroduction to Technical Writing - Priti Gaikwad
Introduction to Technical Writing - Priti Gaikwad
 
Introduction to Selection control structures in C++
Introduction to Selection control structures in C++ Introduction to Selection control structures in C++
Introduction to Selection control structures in C++
 
Prgramming paradigms
Prgramming paradigmsPrgramming paradigms
Prgramming paradigms
 
Progress reports
Progress reportsProgress reports
Progress reports
 
Long Reports
Long ReportsLong Reports
Long Reports
 
C basics 4 std11(GujBoard)
C basics 4 std11(GujBoard)C basics 4 std11(GujBoard)
C basics 4 std11(GujBoard)
 
Lecture 04 writing a memorandum
Lecture 04 writing a memorandumLecture 04 writing a memorandum
Lecture 04 writing a memorandum
 
FOUR DIFFERENT TYPES OF WRITING STYLES
FOUR DIFFERENT TYPES OF WRITING STYLESFOUR DIFFERENT TYPES OF WRITING STYLES
FOUR DIFFERENT TYPES OF WRITING STYLES
 
The Linux Scheduler: a Decade of Wasted Cores
The Linux Scheduler: a Decade of Wasted CoresThe Linux Scheduler: a Decade of Wasted Cores
The Linux Scheduler: a Decade of Wasted Cores
 
Dictionary, encyclopedia and thesaurus
Dictionary, encyclopedia and thesaurusDictionary, encyclopedia and thesaurus
Dictionary, encyclopedia and thesaurus
 
Essay structure
Essay structure Essay structure
Essay structure
 
Control Flow Statements
Control Flow Statements Control Flow Statements
Control Flow Statements
 
C++
C++C++
C++
 
ReactJS presentation.pptx
ReactJS presentation.pptxReactJS presentation.pptx
ReactJS presentation.pptx
 
Citing sources--a review
Citing sources--a reviewCiting sources--a review
Citing sources--a review
 
Intro to c++
Intro to c++Intro to c++
Intro to c++
 
Unit 2 computer software
Unit 2 computer softwareUnit 2 computer software
Unit 2 computer software
 
How to execute a C program
How to execute a C  program How to execute a C  program
How to execute a C program
 

Viewers also liked

Employee appraisal comments sample
Employee appraisal comments sampleEmployee appraisal comments sample
Employee appraisal comments sample
thorstenfinkmen
 
Employee comments on performance appraisal
Employee comments on performance appraisalEmployee comments on performance appraisal
Employee comments on performance appraisal
tommylong551
 
UTPL Describing good teachers
UTPL Describing good teachersUTPL Describing good teachers
UTPL Describing good teachersUTPL UTPL
 
Documentation avoidance for developers
Documentation avoidance for developersDocumentation avoidance for developers
Documentation avoidance for developers
Peter Hilton
 
Employee appraisal examples
Employee appraisal examplesEmployee appraisal examples
Employee appraisal examples
didierdeschamps
 
Performance Appraisal Effectiveness Techniques
Performance Appraisal Effectiveness TechniquesPerformance Appraisal Effectiveness Techniques
Performance Appraisal Effectiveness Techniques
Art Flores
 
Process-oriented reactive service architecture
Process-oriented reactive service architectureProcess-oriented reactive service architecture
Process-oriented reactive service architecture
Peter Hilton
 
About "Apache Cassandra"
About "Apache Cassandra"About "Apache Cassandra"
About "Apache Cassandra"
Jihyun Ahn
 
HTTP demystified for web developers
HTTP demystified for web developersHTTP demystified for web developers
HTTP demystified for web developers
Peter Hilton
 
Writing the docs
Writing the docsWriting the docs
Writing the docs
Mikko Ohtamaa
 
From legacy to DDD - 5 starting steps
From legacy to DDD - 5 starting stepsFrom legacy to DDD - 5 starting steps
From legacy to DDD - 5 starting steps
Andrzej Krzywda
 
Tom and jef’s awesome modellathon
Tom and jef’s awesome modellathonTom and jef’s awesome modellathon
Tom and jef’s awesome modellathon
Tom Janssens
 
Selling ddd
Selling dddSelling ddd
Selling ddd
Tom Janssens
 
Death to project documentation with eXtreme Programming
Death to project documentation with eXtreme ProgrammingDeath to project documentation with eXtreme Programming
Death to project documentation with eXtreme Programming
Alex Fernandez
 
Internship experience
Internship experienceInternship experience
Internship experiencemsriramca
 
Domain-Driven Design in legacy application
Domain-Driven Design in legacy applicationDomain-Driven Design in legacy application
Domain-Driven Design in legacy application
Cyrille Martraire
 
From legacy to DDD (slides for the screencast)
From legacy to DDD (slides for the screencast)From legacy to DDD (slides for the screencast)
From legacy to DDD (slides for the screencast)
Andrzej Krzywda
 
Evolving legacy to microservices and ddd
Evolving legacy to microservices and dddEvolving legacy to microservices and ddd
Evolving legacy to microservices and ddd
Marcos Vinícius
 
Simplifying your design with higher-order functions
Simplifying your design with higher-order functionsSimplifying your design with higher-order functions
Simplifying your design with higher-order functionsSamir Talwar
 
Clean Code
Clean CodeClean Code
Clean Code
Hendrik Ebel
 

Viewers also liked (20)

Employee appraisal comments sample
Employee appraisal comments sampleEmployee appraisal comments sample
Employee appraisal comments sample
 
Employee comments on performance appraisal
Employee comments on performance appraisalEmployee comments on performance appraisal
Employee comments on performance appraisal
 
UTPL Describing good teachers
UTPL Describing good teachersUTPL Describing good teachers
UTPL Describing good teachers
 
Documentation avoidance for developers
Documentation avoidance for developersDocumentation avoidance for developers
Documentation avoidance for developers
 
Employee appraisal examples
Employee appraisal examplesEmployee appraisal examples
Employee appraisal examples
 
Performance Appraisal Effectiveness Techniques
Performance Appraisal Effectiveness TechniquesPerformance Appraisal Effectiveness Techniques
Performance Appraisal Effectiveness Techniques
 
Process-oriented reactive service architecture
Process-oriented reactive service architectureProcess-oriented reactive service architecture
Process-oriented reactive service architecture
 
About "Apache Cassandra"
About "Apache Cassandra"About "Apache Cassandra"
About "Apache Cassandra"
 
HTTP demystified for web developers
HTTP demystified for web developersHTTP demystified for web developers
HTTP demystified for web developers
 
Writing the docs
Writing the docsWriting the docs
Writing the docs
 
From legacy to DDD - 5 starting steps
From legacy to DDD - 5 starting stepsFrom legacy to DDD - 5 starting steps
From legacy to DDD - 5 starting steps
 
Tom and jef’s awesome modellathon
Tom and jef’s awesome modellathonTom and jef’s awesome modellathon
Tom and jef’s awesome modellathon
 
Selling ddd
Selling dddSelling ddd
Selling ddd
 
Death to project documentation with eXtreme Programming
Death to project documentation with eXtreme ProgrammingDeath to project documentation with eXtreme Programming
Death to project documentation with eXtreme Programming
 
Internship experience
Internship experienceInternship experience
Internship experience
 
Domain-Driven Design in legacy application
Domain-Driven Design in legacy applicationDomain-Driven Design in legacy application
Domain-Driven Design in legacy application
 
From legacy to DDD (slides for the screencast)
From legacy to DDD (slides for the screencast)From legacy to DDD (slides for the screencast)
From legacy to DDD (slides for the screencast)
 
Evolving legacy to microservices and ddd
Evolving legacy to microservices and dddEvolving legacy to microservices and ddd
Evolving legacy to microservices and ddd
 
Simplifying your design with higher-order functions
Simplifying your design with higher-order functionsSimplifying your design with higher-order functions
Simplifying your design with higher-order functions
 
Clean Code
Clean CodeClean Code
Clean Code
 

Similar to How to write good comments

How to write maintainable code - Peter Hilton - Codemotion Amsterdam 2017
How to write maintainable code - Peter Hilton - Codemotion Amsterdam 2017How to write maintainable code - Peter Hilton - Codemotion Amsterdam 2017
How to write maintainable code - Peter Hilton - Codemotion Amsterdam 2017
Codemotion
 
Voxxed Days Thessaloniki 2016 - Documentation Avoidance
Voxxed Days Thessaloniki 2016 - Documentation AvoidanceVoxxed Days Thessaloniki 2016 - Documentation Avoidance
Voxxed Days Thessaloniki 2016 - Documentation Avoidance
Voxxed Days Thessaloniki
 
Good code, Bad Code
Good code, Bad CodeGood code, Bad Code
Good code, Bad Codejosedasilva
 
Best Practices in Software Development
Best Practices in Software DevelopmentBest Practices in Software Development
Best Practices in Software Development
André Pitombeira
 
Getting Started with Scripts #HeroConf London 2015
Getting Started with Scripts #HeroConf London 2015Getting Started with Scripts #HeroConf London 2015
Getting Started with Scripts #HeroConf London 2015
Amy Bishop
 
CPP03 - Repetition
CPP03 - RepetitionCPP03 - Repetition
CPP03 - Repetition
Michael Heron
 
An Introduction To Software Development - Implementation
An Introduction To Software Development - ImplementationAn Introduction To Software Development - Implementation
An Introduction To Software Development - Implementation
Blue Elephant Consulting
 
高品質軟體的基本動作 101 + 102 for NUU
高品質軟體的基本動作 101 + 102 for NUU高品質軟體的基本動作 101 + 102 for NUU
高品質軟體的基本動作 101 + 102 for NUU
Su Jan
 
Writing clean code in C# and .NET
Writing clean code in C# and .NETWriting clean code in C# and .NET
Writing clean code in C# and .NET
Dror Helper
 
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
Søren Lund
 
If your code could speak, what would it tell you? Let GitHub Copilot Chat hel...
If your code could speak, what would it tell you? Let GitHub Copilot Chat hel...If your code could speak, what would it tell you? Let GitHub Copilot Chat hel...
If your code could speak, what would it tell you? Let GitHub Copilot Chat hel...
Maxim Salnikov
 
WordCamp US: Clean Code
WordCamp US: Clean CodeWordCamp US: Clean Code
WordCamp US: Clean Code
mtoppa
 
Code smells and Other Malodorous Software Odors
Code smells and Other Malodorous Software OdorsCode smells and Other Malodorous Software Odors
Code smells and Other Malodorous Software Odors
Clint Edmonson
 
Documenting code yapceu2016
Documenting code yapceu2016Documenting code yapceu2016
Documenting code yapceu2016
Søren Lund
 
Whats Newi in C# 8.0
Whats Newi in C# 8.0Whats Newi in C# 8.0
Whats Newi in C# 8.0
Manoj Sharma
 
How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....
Mike Harris
 
The Psychology of C# Analysis
The Psychology of C# AnalysisThe Psychology of C# Analysis
The Psychology of C# Analysis
Coverity
 
Comment soup with a pinch of types, served in a leaky bowl
Comment soup with a pinch of types, served in a leaky bowlComment soup with a pinch of types, served in a leaky bowl
Comment soup with a pinch of types, served in a leaky bowl
Pharo
 
Making Testing Easy w GitHub Copilot.pdf
Making Testing Easy w GitHub Copilot.pdfMaking Testing Easy w GitHub Copilot.pdf
Making Testing Easy w GitHub Copilot.pdf
Applitools
 

Similar to How to write good comments (20)

How to write maintainable code - Peter Hilton - Codemotion Amsterdam 2017
How to write maintainable code - Peter Hilton - Codemotion Amsterdam 2017How to write maintainable code - Peter Hilton - Codemotion Amsterdam 2017
How to write maintainable code - Peter Hilton - Codemotion Amsterdam 2017
 
Voxxed Days Thessaloniki 2016 - Documentation Avoidance
Voxxed Days Thessaloniki 2016 - Documentation AvoidanceVoxxed Days Thessaloniki 2016 - Documentation Avoidance
Voxxed Days Thessaloniki 2016 - Documentation Avoidance
 
Good code, Bad Code
Good code, Bad CodeGood code, Bad Code
Good code, Bad Code
 
Best Practices in Software Development
Best Practices in Software DevelopmentBest Practices in Software Development
Best Practices in Software Development
 
Getting Started with Scripts #HeroConf London 2015
Getting Started with Scripts #HeroConf London 2015Getting Started with Scripts #HeroConf London 2015
Getting Started with Scripts #HeroConf London 2015
 
CPP03 - Repetition
CPP03 - RepetitionCPP03 - Repetition
CPP03 - Repetition
 
An Introduction To Software Development - Implementation
An Introduction To Software Development - ImplementationAn Introduction To Software Development - Implementation
An Introduction To Software Development - Implementation
 
高品質軟體的基本動作 101 + 102 for NUU
高品質軟體的基本動作 101 + 102 for NUU高品質軟體的基本動作 101 + 102 for NUU
高品質軟體的基本動作 101 + 102 for NUU
 
Writing clean code in C# and .NET
Writing clean code in C# and .NETWriting clean code in C# and .NET
Writing clean code in C# and .NET
 
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
 
If your code could speak, what would it tell you? Let GitHub Copilot Chat hel...
If your code could speak, what would it tell you? Let GitHub Copilot Chat hel...If your code could speak, what would it tell you? Let GitHub Copilot Chat hel...
If your code could speak, what would it tell you? Let GitHub Copilot Chat hel...
 
Coding Standards
Coding StandardsCoding Standards
Coding Standards
 
WordCamp US: Clean Code
WordCamp US: Clean CodeWordCamp US: Clean Code
WordCamp US: Clean Code
 
Code smells and Other Malodorous Software Odors
Code smells and Other Malodorous Software OdorsCode smells and Other Malodorous Software Odors
Code smells and Other Malodorous Software Odors
 
Documenting code yapceu2016
Documenting code yapceu2016Documenting code yapceu2016
Documenting code yapceu2016
 
Whats Newi in C# 8.0
Whats Newi in C# 8.0Whats Newi in C# 8.0
Whats Newi in C# 8.0
 
How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....
 
The Psychology of C# Analysis
The Psychology of C# AnalysisThe Psychology of C# Analysis
The Psychology of C# Analysis
 
Comment soup with a pinch of types, served in a leaky bowl
Comment soup with a pinch of types, served in a leaky bowlComment soup with a pinch of types, served in a leaky bowl
Comment soup with a pinch of types, served in a leaky bowl
 
Making Testing Easy w GitHub Copilot.pdf
Making Testing Easy w GitHub Copilot.pdfMaking Testing Easy w GitHub Copilot.pdf
Making Testing Easy w GitHub Copilot.pdf
 

More from Peter Hilton

Naming guidelines for professional programmers
Naming guidelines for professional programmersNaming guidelines for professional programmers
Naming guidelines for professional programmers
Peter Hilton
 
Beautiful code
Beautiful codeBeautiful code
Beautiful code
Peter Hilton
 
E-Prime: English for scientific writing
E-Prime: English for scientific writing E-Prime: English for scientific writing
E-Prime: English for scientific writing
Peter Hilton
 
Meeting-avoidance for self-managing developers
Meeting-avoidance for self-managing developersMeeting-avoidance for self-managing developers
Meeting-avoidance for self-managing developers
Peter Hilton
 
Scaling business app development with Play and Scala
Scaling business app development with Play and ScalaScaling business app development with Play and Scala
Scaling business app development with Play and Scala
Peter Hilton
 
Play framework: lessons learned
Play framework: lessons learnedPlay framework: lessons learned
Play framework: lessons learnedPeter Hilton
 

More from Peter Hilton (6)

Naming guidelines for professional programmers
Naming guidelines for professional programmersNaming guidelines for professional programmers
Naming guidelines for professional programmers
 
Beautiful code
Beautiful codeBeautiful code
Beautiful code
 
E-Prime: English for scientific writing
E-Prime: English for scientific writing E-Prime: English for scientific writing
E-Prime: English for scientific writing
 
Meeting-avoidance for self-managing developers
Meeting-avoidance for self-managing developersMeeting-avoidance for self-managing developers
Meeting-avoidance for self-managing developers
 
Scaling business app development with Play and Scala
Scaling business app development with Play and ScalaScaling business app development with Play and Scala
Scaling business app development with Play and Scala
 
Play framework: lessons learned
Play framework: lessons learnedPlay framework: lessons learned
Play framework: lessons learned
 

Recently uploaded

A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Enhancing Performance with Globus and the Science DMZ
Enhancing Performance with Globus and the Science DMZEnhancing Performance with Globus and the Science DMZ
Enhancing Performance with Globus and the Science DMZ
Globus
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..
UiPathCommunity
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 

Recently uploaded (20)

A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Enhancing Performance with Globus and the Science DMZ
Enhancing Performance with Globus and the Science DMZEnhancing Performance with Globus and the Science DMZ
Enhancing Performance with Globus and the Science DMZ
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 

How to write good comments

  • 2. # Single-line comments in: # BASH, CoffeeScript, Perl, PHP, Python, Ruby, YAML, // C, C++, C#, F#, Java, JavaScript, PHP, -- Haskell, SQL, ; Assembler, Common Lisp, Emacs Lisp, Logo, Scheme, % Erlang, PostScript, Prolog, TeX, ' Visual basic, C FORTRAN, rem BASIC
  • 3. =begin Multi-line comments in: Ruby, =end /* C, C++, Java, JavaScript, PHP */ <!-- HTML, XML --> ### CoffeeScript ### http://rigaux.org/language-study/syntax-across-languages.html#VrsCmmnt
  • 5. What are comments? Comments are annotations in source code, written for programmers who maintain the code. Comments are the only feature common to all* programming languages. Comments are amazingly useful, mainly because we spend more time reading code than writing it. * general purpose languages 5@PeterHilton •
  • 6. What are comments for? ‘Comments are usually added with the purpose of making the source code easier to understand, …’ ‘How best to make use of comments is subject to dispute; different commentators have offered varied and sometimes opposing viewpoints.’ http://en.wikipedia.org/wiki/Comment_(computer_programming) 6@PeterHilton •
  • 7. Who are comments for Comments are, in the first instance, for yourself. This includes your future self, who will thank you for learning to write good comments. Your colleagues will also thank you, especially if you’re better at it than them, and write theirs too. X@PeterHilton •
  • 8. What is the problem? X@PeterHilton • Writing comments is harder than 
 writing or coding (because it’s both) Programmers* don’t like writing (or talking about writing comments) * most programmers
  • 10. Existential angst kitten wants to know why? bontempscharly / CC BY 2.0
  • 11. // Returns zero for dead kittens (not cute). // Throws IllegalArgumentException for cats // that are too old to be kittens. def estimateCuteness(kitten: Kitten): Int = ??? case class Kitten( photo: URL, cutenessScore: Int, age: Duration) // Photo of a kitten to console // a trader after a loss, with // cuteness proportional to the // magnitude of the loss. // Returns a cuteness score estimate for // non-dead kittens less than one year old.
  • 12. class Kitten attr_accessor :photoUrl attr_accessor :cutenessScore attr_accessor :age def initialize photoUrl, cutenessScore, age @photoUrl = photoUrl @cutenessScore = cutenessScore @age = age end end # Photo of a kitten to console a trader after a loss, with # cuteness proportional to the magnitude of the loss.
  • 13. Explain why the code exists Good comments answer the ‘why?’ questions in a way that good code cannot. Code cannot explain its own existence. When should I use this code? What are the alternatives to this code? 10@PeterHilton •
  • 14. def estimateCuteness kitten # TODO end # Returns an estimated cuteness score for a kitten. # Returns an estimated cuteness score for a kitten. # * Returns zero for dead kittens (not cute). # * Raises an exception for cats that are too old to be kittens.
  • 15. Pre-conditions, restrictions and limitations Explain pre-conditions, needed for working code, e.g. valid values Explain restrictions - when the code won’t work, e.g. values that are not supported Tell me when I shouldn’t use this code Explain why pre-conditions and limitations apply. 12@PeterHilton •
  • 16.
  • 17. Comments are the introduction Lengthy code needs an introduction, just like a book or long document, to explain: purpose - what it’s for scope - who it’s for and when it applies summary - what it’s about http://hilton.org.uk/blog/comments-are-the-introduction 14@PeterHilton •
  • 18. Explain implementation choices Why is that the right functionality? Why is it implemented this way? Why wasn’t it done the obvious way? Exceptions to coding standards often require a comment to say what’s going on. 15@PeterHilton •
  • 19. /** * Deprecated: Use a kitten instead */ case class ConsolationPuppy(photo: URL, cuteness: Score, age: Duration) /** * We use kittens instead of puppies, * which turn out to be less cute. */ case class ConsolationKitten(photo: URL, cuteness: Score, age: Duration)
  • 20. Comment the code that isn’t there Sometimes, you need to talk about code that isn’t there any more: Failed approaches Code before optimisation Functionality that became superfluous X@PeterHilton •
  • 21. Concrete API usage examples Using an API can be difficult without having usage examples. This shouldn’t apply to application code, because there should always be usages X@PeterHilton •
  • 22. Compensate for different levels of fluency in the team Write for your audience - including the future team, and especially on a multi-disciplinary team Don’t mix jargon from different areas - from both problem domain and solution domain New team members shouldn’t need to understand everything to read anything 16@PeterHilton •
  • 23. Summary of useful comments 1. Purpose 2. Scope introduction 3. Summary 4. Limitations 5. Alternatives 6. Examples 7. Explanations for new team members http://hilton.org.uk/blog/3-kinds-of-good-comments 17@PeterHilton • }
  • 24. How to write good comments
  • 25. No comments at all is giving up. You can do better than that. @PeterHilton • X
  • 26. Documentation comments Comments can document code’s public interface - how other programmers will use the code. Write a one-sentence comment for every: class and public method (or function) Use consistent grammar for documentation comments, e.g. ‘Returns…’ X@PeterHilton •
  • 27. Discover which comments are hard to write, and why If a comment is easy to write, then that code probably doesn’t need a comment (right now). How to test code for maintainability: 1. Write a one-sentence comment,
 for every class and method (or function). 2. (there is no 2) 19@PeterHilton •
  • 28. Rewriting comments It is unreasonable to expect to write a comment once and never have to edit it. Comments require review, rewrites and refactoring, just like code. Include comments in code review. Comments are not separate from code. 20@PeterHilton •
  • 29. Deleting comments Improving code includes deleting comments, 
 as well as deleting code. Delete the comments you don’t need, to 
 leave more room for the ones you do need. Refactor the code, then repeat. http://hilton.org.uk/blog/how-to-comment-code 21@PeterHilton •
  • 30. ‘A common fallacy is to assume authors of incomprehensible code will somehow be able to express themselves lucidly and clearly in comments.’ @KevlinHenney X@PeterHilton •
  • 31. Acknowledge that writing (comments) is a specialist skill On a cross-functional development team, not everyone is good at visual design. The same goes for writing about code. Work out who is a better writer. Get help with writing comments. X@PeterHilton •
  • 33. Bad code and comments Comments sometimes compensate for bad code. Bad code is usually benefits from comments. Improving bad code usually makes some comments unnecessary. (But don’t remove useful comments without actually improving the code first.) 23@PeterHilton •
  • 34. Refactoring to avoid the need for comments X@PeterHilton • Better modelling and naming communicate purpose a.k.a intention. Domain-Driven Design is your friend Avoid primitive types in APIs Extracting and naming local expressions (and encapsulating logic in functions) makes code its own summary.
  • 35. Adding tests Tests can communicate requirements and intention, and demonstrate using an API … but not necessarily Tests have a different primary purpose and are separate from the code they test … and might even be written first X@PeterHilton •
  • 36. Don’t write bad comments! 1. Don’t say what the code does
 (because the code already says that) 2. Don’t explain bad code & awkward logic
 (refactor the code to make it clear) 3. Don’t add too many comments
 (it’s messy and they’ll get out of date) 4. Write unit tests instead 24@PeterHilton •
  • 37. 7 sins of bad comments 25@PeterHilton • 1. Errors in syntax or grammar 2. Out-of-date with respect to the code 3. Verbose, taking up too much space 4. Too numerous, adding clutter 5. Duplicating the code 6. Explaining awkward logic 7. Contradicting the code http://hilton.org.uk/blog/7-ways-to-write-bad-comments
  • 38. Refactoring to avoid the need for comments Better modelling and naming communicate purpose a.k.a intention. Domain-Driven Design is your friend Avoid primitive types in APIs Extracting and naming local expressions (and encapsulating logic in functions) makes code its own summary. X@PeterHilton •
  • 39. Adding tests Tests can communicate requirements and intention, and demonstrate using an API … but not necessarily Tests have a different primary purpose and are separate from the code they test … and might even be written first X@PeterHilton •
  • 41. Comments are hard Not everyone is good at writing, and technical writing is a specialism like user interface design. Writing comments is harder than writing or coding (because it includes both). Programmers* don’t like writing, which includes writing comments. * some programmers 27@PeterHilton •
  • 42. How to write good comments (summary) 1. Try to write good code first. 2. Write a one-sentence comment. 3. Refactor the code (make it easier to understand). 4. Delete unnecessary comments. 5. Rewrite bad comments
 (all good writing requires rewriting) 6. Add detail where needed. 7. Do it for your future self. 28@PeterHilton •
  • 43. When programming, use the best language for the job. Sometimes, it’s English. @PeterHilton • X