44
@PeterHilton http://hilton.org.uk/ How to write good comments

How to write good comments

Embed Size (px)

Citation preview

Page 1: How to write good comments

@PeterHilton

http://hilton.org.uk/

How to write good comments

Page 2: 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

Page 3: How to write good comments

=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

Page 4: How to write good comments

Code comments

Page 5: How to write good 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 •

Page 6: How to write good comments

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 •

Page 7: How to write good comments

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 •

Page 8: How to write good comments

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

Page 9: How to write good comments

Kinds of useful comments

Page 10: How to write good comments

Existential angst kitten wants to know why?

bontempscharly / CC BY 2.0

Page 11: How to write good comments

// 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.

Page 12: How to write good comments

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.

Page 13: How to write good comments

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 •

Page 14: How to write good comments

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.

Page 15: How to write good comments

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 •

Page 16: How to write good comments
Page 17: How to write good comments

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 •

Page 18: How to write good comments

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 •

Page 19: How to write good comments

/** * 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)

Page 20: How to write good comments

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 •

Page 21: How to write good comments

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 •

Page 22: How to write good comments

Compensate for different levels of fluency in the teamWrite 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 •

Page 23: How to write good comments

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 •

}

Page 24: How to write good comments

How to write good comments

Page 25: How to write good comments

No comments at all is giving up. You can do better than that.

@PeterHilton • X

Page 26: How to write good comments

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 •

Page 27: How to write good comments

Discover which comments are hard to write, and whyIf 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 •

Page 28: How to write good comments

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 •

Page 29: How to write good comments

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 •

Page 30: How to write good comments

‘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 •

Page 31: How to write good comments

Acknowledge that writing (comments) is a specialist skillOn 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 •

Page 32: How to write good comments

Bad comments

Page 33: How to write good 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 •

Page 34: How to write good comments

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.

Page 35: How to write good comments

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 •

Page 36: How to write good comments

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 instead24@PeterHilton •

Page 37: How to write good comments

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

Page 38: How to write good 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 •

Page 39: How to write good comments

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 •

Page 40: How to write good comments

Summary

Page 41: How to write good comments

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 •

Page 42: How to write good comments

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 •

Page 43: How to write good comments

When programming, use the best language for the job. Sometimes, it’s English.

@PeterHilton • X

Page 44: How to write good comments

@PeterHilton

http://hilton.org.uk/