commenting code beyond common wisdom · very interested in writing maintainable software writing...

28
Commenting code Beyond common wisdom PyCon DE and PyData Stefan Schwarzer, SSchwarzer.com [email protected] Berlin, Germany, 2019-10-10

Upload: others

Post on 22-Aug-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Commenting code Beyond common wisdom · Very interested in writing maintainable software Writing rather many, sometimes extensive comments Found online articles or statements that

Commenting codeBeyond common wisdom

PyConDE and PyData

Stefan Schwarzer, [email protected]

Berlin, Germany, 2019-10-10

Page 2: Commenting code Beyond common wisdom · Very interested in writing maintainable software Writing rather many, sometimes extensive comments Found online articles or statements that

About me

Using Python since 1999

Full-time software developer since 2000

Freelancer since 2005

Book “Workshop Python”, Addison-Wesley,using the then brand new Python 2.2 ;-)

About 15 conference talks

Maintainer of ftputil (high-level FTP client library)since 2002

Commenting code – beyond common wisdom 2 / 28

Page 3: Commenting code Beyond common wisdom · Very interested in writing maintainable software Writing rather many, sometimes extensive comments Found online articles or statements that

Overview

Introduction

Common wisdom

Comment more – or less?

Tips for good comments

Comments vs. commit messages

Commenting code – beyond common wisdom 3 / 28

Page 4: Commenting code Beyond common wisdom · Very interested in writing maintainable software Writing rather many, sometimes extensive comments Found online articles or statements that

Introduction

motivation, purposes of comments

Page 5: Commenting code Beyond common wisdom · Very interested in writing maintainable software Writing rather many, sometimes extensive comments Found online articles or statements that

Motivation for this talk

Very interested in writing maintainable software

Writing rather many, sometimes extensive comments

Found online articles or statements that recommend usingfew or even no comments

How to resolve this contradiction?

Commenting code – beyond common wisdom 5 / 28

Page 6: Commenting code Beyond common wisdom · Very interested in writing maintainable software Writing rather many, sometimes extensive comments Found online articles or statements that

Why comments?

Comments help with

Understanding the software better→ make changes more safely

Understanding the software faster→ make changes faster – but still correctly!

(even if the software design is already quite good)

Commenting code – beyond common wisdom 6 / 28

Page 7: Commenting code Beyond common wisdom · Very interested in writing maintainable software Writing rather many, sometimes extensive comments Found online articles or statements that

Common wisdom

why vs. what/how, extract functions, better identifier names,comments become obsolete, comments deviate from code

Page 8: Commenting code Beyond common wisdom · Very interested in writing maintainable software Writing rather many, sometimes extensive comments Found online articles or statements that

“Document the ‘why’, not the ‘what/how’ ”

Mostly yes

“Section comments” can help, too

Idea: describe a code section on a higher abstraction level,even if you could derive the same information from readingthe code

Commenting code – beyond common wisdom 8 / 28

Page 9: Commenting code Beyond common wisdom · Very interested in writing maintainable software Writing rather many, sometimes extensive comments Found online articles or statements that

“Document the ‘why’, not the ‘what/how’ ”Example of a section comment

# Classify the object or its descriptor.

if isinstance(dict_obj, (staticmethod, types.BuiltinMethodType)):

kind = "static method"

obj = dict_obj

elif isinstance(dict_obj, (classmethod,

types.ClassMethodDescriptorType)):

kind = "class method"

obj = dict_obj

elif isinstance(dict_obj, property):

kind = "property"

obj = dict_obj

elif isroutine(obj):

kind = "method"

else:

kind = "data"

(from Python standard library, inspect module)

Commenting code – beyond common wisdom 9 / 28

Page 10: Commenting code Beyond common wisdom · Very interested in writing maintainable software Writing rather many, sometimes extensive comments Found online articles or statements that

“Extract a function/method instead of writing comments”

Pro:

Individual function is shorter, probably easier to read

Extraction introduces new (hopefully meaningful) namesfor function/method and parameters

Con:

Code becomes more fragmented

Overall understanding doesn’t necessarily get better

Reader has to find out from where the extractedfunction/method is called

Commenting code – beyond common wisdom 10 / 28

Page 11: Commenting code Beyond common wisdom · Very interested in writing maintainable software Writing rather many, sometimes extensive comments Found online articles or statements that

“Extract a function/method instead of writing comments”

class MyClass:

...

# Is this called from anywhere else in the class?

# Maybe from derived classes?

def _new_method(self, foo, bar):

...

return result

def original_method(self):

...

foo = ...

...

bar = ...

return self._new_method(foo, bar)

...

Commenting code – beyond common wisdom 11 / 28

Page 12: Commenting code Beyond common wisdom · Very interested in writing maintainable software Writing rather many, sometimes extensive comments Found online articles or statements that

“Use better names instead of writing comments”aka “Use a better name instead of commenting a bad name”

Why not use a better name and comment?

Improve design, including better names

If something still needs clarification, add comments

Commenting code – beyond common wisdom 12 / 28

Page 13: Commenting code Beyond common wisdom · Very interested in writing maintainable software Writing rather many, sometimes extensive comments Found online articles or statements that

“Comments easily become obsolete”

Take comments as seriously as other code→ Pay attention to updating comments

“I can’t test comments”Does that mean you don’t take code seriously only becauseyou can’t test it? ;-)

Comments are more likely to become obsolete the furtherthey are away from the code they apply to→ If you can, prefer comments in functions/methods

over comments on the class/module level

Commenting code – beyond common wisdom 13 / 28

Page 14: Commenting code Beyond common wisdom · Very interested in writing maintainable software Writing rather many, sometimes extensive comments Found online articles or statements that

“Avoid comments because they could deviatefrom the code”

aka “Contradictory comments are worse than no comments”

Pay attention to updating comments (see above)

Since the comment should be on a higher abstraction level,it’s likely that the code is wrong and the comment tells youwhat was intended

Sometimes deviations tell you something aboutdesign problems in your code

Usually only a small fraction of comments ends upcontradictory, so overall you’re better off with comments :-)

Commenting code – beyond common wisdom 14 / 28

Page 15: Commenting code Beyond common wisdom · Very interested in writing maintainable software Writing rather many, sometimes extensive comments Found online articles or statements that

Comment more – or less?

don’t repeat the code, development context,developer knowledge, recommendation

Page 16: Commenting code Beyond common wisdom · Very interested in writing maintainable software Writing rather many, sometimes extensive comments Found online articles or statements that

Don’t repeat the code

Do not comment when it would repeat the codeon the same abstraction level

# Increase index by 2.

index += 2

# Add client to clients list.

clients.append(client)

This is ok (higher abstraction level)

# Never expire

max_age = None

Commenting code – beyond common wisdom 16 / 28

Page 17: Commenting code Beyond common wisdom · Very interested in writing maintainable software Writing rather many, sometimes extensive comments Found online articles or statements that

Development context

Reasonable amount and detailedness of commentsdepend on development context

Developer knowledge

Software size

Software complexity

Application vs. library

Team size

Team fluctuation

Time between modifications

. . .

Commenting code – beyond common wisdom 17 / 28

Page 18: Commenting code Beyond common wisdom · Very interested in writing maintainable software Writing rather many, sometimes extensive comments Found online articles or statements that

Developer knowledge

There are many ways a developer can be more or lessexperienced/knowledgeable

General programming knowledge

Programming language knowledge

Problem domain knowledge

Company knowledge

Architecture knowledge

Perhaps more?

Do pair programming and code reviews for knowledge transfer!

Commenting code – beyond common wisdom 18 / 28

Page 19: Commenting code Beyond common wisdom · Very interested in writing maintainable software Writing rather many, sometimes extensive comments Found online articles or statements that

More or less?

(If you really want) you can ignore existing comments

But you can’t conjure up comments which aren’t there :-)

→ If in doubt, comment rather more than less!

Commenting code – beyond common wisdom 19 / 28

Page 20: Commenting code Beyond common wisdom · Very interested in writing maintainable software Writing rather many, sometimes extensive comments Found online articles or statements that

Good comments

(in my opinion)

Page 21: Commenting code Beyond common wisdom · Very interested in writing maintainable software Writing rather many, sometimes extensive comments Found online articles or statements that

Tips for good comments

Comments should make the code easier to understand

Comment what a reader might want to know

Comment what you found out while working on the code

Comment what isn’t obvious. Besides, what’s obvious to youmay not be obvious to others ;-)

Check comments for ambiguity(pronouns, singular/plural, sentence structure, . . . )

Comment to avoid “simplifications” that could break the code

Commenting code – beyond common wisdom 21 / 28

Page 22: Commenting code Beyond common wisdom · Very interested in writing maintainable software Writing rather many, sometimes extensive comments Found online articles or statements that

Tips for good commentsExample for avoiding “simplification”

def _dir(self, path):

"""

Return a directory listing as made by FTP’s ‘LIST‘ command

as a list of strings.

"""

# Don’t use ‘self.path.isdir‘ in this method because that

# would cause a call of ‘(l)stat‘ and thus a call to ‘_dir‘,

# so we would end up with an infinite recursion.

...

(from ftputil library, host module)

Commenting code – beyond common wisdom 22 / 28

Page 23: Commenting code Beyond common wisdom · Very interested in writing maintainable software Writing rather many, sometimes extensive comments Found online articles or statements that

Tips for good comments

Start comments with an uppercase letter. End sentenceswith a period. This makes it easier to extend comments.

Use XXX, TODO and FIXME comments. Don’t pretendeverything is fine when you know it’s not the case.

If necessary, adjust syntax highlighting so that comments areeasy to read. This helps against comments getting outdated.

If you add an empty line to separate code sections,consider adding a comment on the section instead :-)

Commenting code – beyond common wisdom 23 / 28

Page 24: Commenting code Beyond common wisdom · Very interested in writing maintainable software Writing rather many, sometimes extensive comments Found online articles or statements that

Comments vs. commit messages

Page 25: Commenting code Beyond common wisdom · Very interested in writing maintainable software Writing rather many, sometimes extensive comments Found online articles or statements that

Comments vs. commit messages

Comments are far more visible than commit messages→ Comment what a reader must not miss

Explain in commit messages why you did not do something(for example designs you considered and why you chose oneover the others)

Put information in commit messages a code reviewermight want to know (unless already covered in comments)

Commenting code – beyond common wisdom 25 / 28

Page 26: Commenting code Beyond common wisdom · Very interested in writing maintainable software Writing rather many, sometimes extensive comments Found online articles or statements that

Literature

Page 27: Commenting code Beyond common wisdom · Very interested in writing maintainable software Writing rather many, sometimes extensive comments Found online articles or statements that

Literature

The art of readable codeDustin Boswell, Trevor Foucher

A philosophy of software designJohn Ousterhoutsee also his talk athttps://www.youtube.com/watch?v=bmSAYlu0NcY

How to write a Git commit messageChris Beamshttps://chris.beams.io/posts/git-commit(also applies to other VCSs)

Line by line – how to edit your own writingClaire Kehrwald Cook

Commenting code – beyond common wisdom 27 / 28

Page 28: Commenting code Beyond common wisdom · Very interested in writing maintainable software Writing rather many, sometimes extensive comments Found online articles or statements that

Thank you for your attention! :-)

Questions?

Remarks?

Discussion?

[email protected]

https://sschwarzer.com

Commenting code – beyond common wisdom 28 / 28