Don't Write Comments

CodeAesthetic
16 Jan 202305:55

Summary

TLDRThe video script advocates for minimal use of comments in code, suggesting that clarity should be achieved through better code design and naming conventions. It emphasizes the importance of using constants, refactoring complex conditions, and leveraging types to convey information that would otherwise require comments. The speaker highlights the issues with comments, such as their tendency to become outdated and the lack of a system to ensure their accuracy. Instead, the script promotes high-quality code documentation that describes the system's architecture and public APIs, which can be generated by tools like Doxygen, pydoc, and JavaDoc to keep in sync with the code. The speaker acknowledges that comments may still be necessary in certain cases, such as explaining non-obvious performance optimizations or referencing specific algorithms, but overall, code should be self-explanatory.

Takeaways

  • πŸ“ Avoid writing comments in code whenever possible, as they can become outdated and unreliable.
  • πŸ” Use meaningful names for variables and constants to make code self-explanatory, reducing the need for comments.
  • πŸ“ˆ Simplify complex conditions by breaking them down into named variables, making the code more readable.
  • πŸ”„ If a condition is complex, consider refactoring it into its own function for clarity.
  • πŸ”’ Types can eliminate the need for comments by conveying ownership and responsibility, as seen in C++ with unique_ptr.
  • πŸ”„ Use types to express optionality or special conditions, such as returning an optional int, which makes the code safer.
  • 🚫 Comments can be misleading and are not checked by tools, unlike code, which has tests and compiler checks.
  • πŸ“– Focus on high-quality code documentation that describes the system's architecture and public APIs, rather than internal workings.
  • πŸ”§ Tools like Doxygen, pydoc, and JavaDoc help generate documentation from code, keeping it in sync with changes.
  • πŸ“‹ Document class or API expectations, such as thread safety and error conditions, to help users and implementers.
  • πŸ” There are rare cases where comments are necessary, such as explaining non-obvious performance optimizations or referencing algorithms.

Q & A

  • What is the speaker's stance on writing comments in code?

    -The speaker believes that comments in code should be avoided most of the time, as they can become outdated and are not as reliable as the code itself.

  • How can a constant be used to improve code readability?

    -A constant can replace a magic number, like '5', making the code more self-explanatory and easier to understand without the need for comments.

  • What is the speaker's suggestion for handling complex conditions in code?

    -The speaker suggests simplifying or refactoring the code to make it more understandable, or moving the complex condition to its own function.

  • How do types in C++ help reduce the need for comments?

    -Types like unique_ptr in C++ can convey ownership and responsibility for memory management, eliminating the need for comments that might otherwise explain this.

  • What is the difference between code documentation and comments?

    -Code documentation describes the high-level architecture and public APIs, focusing on how to use the code, while comments explain the internal workings of the code.

  • Why are comments less reliable than code?

    -Comments can become outdated when code changes, and there are no systematic tools to ensure their accuracy like there are for code, making them less reliable.

  • What is the speaker's approach to understanding code?

    -The speaker prefers to read the code itself rather than the comments, as code cannot lie and is a more precise expression of intent.

  • What are some cases where the speaker believes comments might still be necessary?

    -Comments might be useful for explaining non-obvious performance optimizations or referencing specific algorithms or mathematical principles.

  • How can code be made more 'human'?

    -By improving the API design and making the code more intuitive, it can express intent more clearly without the need for human language descriptions.

  • What is the speaker's view on the future of programming and AI?

    -The speaker humorously suggests that while some believe AI will replace the need for code, they argue that code is a precise way of writing a specification and that AI might lead to sociopolitical challenges.

  • What tools are mentioned for generating documentation from code?

    -Tools like Doxygen, pydoc, and JavaDoc are mentioned as they can generate documentation directly from code files, helping to keep the documentation in sync with the code.

Outlines

00:00

πŸ“ The Case Against Code Comments

This paragraph discusses the author's opinion against writing comments in code most of the time. It argues that comments can be redundant and suggests using constants and better code structure to convey the same information. The author emphasizes the importance of simplifying complex conditions and using types to make code self-explanatory, reducing the need for comments. It also highlights the problems with comments, such as them getting outdated or being ignored, and contrasts them with code documentation, which is considered more valuable and useful for understanding how to use the code.

05:02

πŸ€– The Future of Code and AI

The second paragraph presents a hypothetical scenario where a developer is told that in the future, code will be written by AI based on specifications. The author disagrees with this notion, stating that code is a precise way of expressing a specification and that AI's impact on jobs is a separate issue. The paragraph suggests that instead of relying on comments, the code itself should be made more understandable, and it asks the audience for their thoughts on when comments might be necessary.

Mindmap

Keywords

πŸ’‘Comments in code

Comments are annotations in the code that do not affect the program's execution. The video suggests that comments are often unnecessary and can be replaced with clearer code or better variable naming. For example, instead of commenting on the purpose of the value '5', a constant could be defined to represent it, making the code self-explanatory.

πŸ’‘Code readability

Code readability refers to how easily and quickly a programmer can understand the purpose of the code. The video emphasizes the importance of writing code that is readable without relying on comments. It suggests using meaningful variable names and refactoring complex code to improve readability, as seen when the if statement is simplified and the comment becomes redundant.

πŸ’‘Refactoring

Refactoring is the process of restructuring existing computer code without changing its external behavior. The video advocates for refactoring complex code to make it simpler and more understandable, which in turn reduces the need for comments. An example given is simplifying a complex condition by breaking it down into named variables.

πŸ’‘Type system

A type system is a way to classify data and ensure that operations on data are valid. The video highlights how using types, like unique_ptr in C++, can convey information that would otherwise be in comments, such as ownership of memory. This makes the code safer and easier to understand without the need for additional documentation.

πŸ’‘Ownership

In programming, ownership refers to which part of the code is responsible for managing the lifecycle of an object, including deallocating memory. The video discusses how the lack of built-in memory management in C++ historically required comments to indicate ownership. However, with the introduction of types like unique_ptr, the responsibility is now explicitly encoded in the type, eliminating the need for comments.

πŸ’‘Optional types

Optional types are used to represent the presence or absence of a value. The video suggests using optional types, like optional int, to indicate that a function might not return a value. This approach makes the possibility of a missing value clear to the user and avoids the need for a comment explaining the same.

πŸ’‘Code documentation

Code documentation is the practice of providing high-level descriptions of a system's architecture and public APIs. Unlike comments, which explain the internal workings of code, documentation focuses on how to use the code. The video promotes the use of tools like Doxygen, pydoc, and JavaDoc that generate documentation from code files, ensuring that the documentation stays in sync with the code.

πŸ’‘APIs

APIs (Application Programming Interfaces) are sets of rules and protocols that allow different software applications to communicate with each other. The video stresses the importance of documenting APIs to help users understand how to interact with them and what to expect in terms of thread safety, possible states, or error conditions.

πŸ’‘Static analysis

Static analysis is a method of debugging a program by examining its code without actually running it. The video humorously suggests that a static analysis tool using AI could one day check if comments match the code, which would be a significant advancement in maintaining the accuracy of comments.

πŸ’‘Non-obvious performance optimizations

Sometimes, code is written in a non-intuitive way to optimize performance. The video acknowledges that in such cases, comments can be useful to explain the rationale behind the performance-oriented code. An example could be a comment explaining why a certain loop is unrolled for speed.

πŸ’‘Algorithms and mathematical principles

The video mentions that if code utilizes a specific algorithm or mathematical principle, it might be appropriate to include a comment with a reference to the source. This helps future maintainers understand the underlying logic and verify the correctness of the implementation.

Highlights

The speaker suggests that comments in code are often unnecessary and can be replaced with better code practices.

Using constants instead of magic numbers can improve code readability without the need for comments.

Complex code conditions can be simplified or refactored, reducing the need for explanatory comments.

Naming parts of expressions with variables can make the code self-explanatory, eliminating the need for comments.

Moving complex conditions to their own functions can clarify code without relying on comments.

Using types like unique_ptr in C++ can convey ownership information without comments, and enforce it at compile time.

The speaker advocates for using types like optional int to indicate the possibility of missing values, instead of relying on comments.

Comments can become outdated and may not be updated with code changes, unlike code which has built-in checks.

The speaker prefers reading code over comments to understand its functionality, as comments can be untrustworthy.

Code documentation is preferred over inline comments for describing the architecture and public APIs of a system.

Tools like Doxygen, pydoc, and JavaDoc generate documentation from code, helping to keep it in sync with the codebase.

Documenting class or API expectations, such as thread safety and error conditions, is important for API consumers and implementers.

There are cases where comments are necessary, such as explaining non-obvious performance optimizations or referencing mathematical principles.

The speaker believes that code is a more precise way of expressing intent than comments and that comments should be used sparingly.

The speaker humorously references a comic strip about the future of programming, where code is seen as a precise form of specification.

The speaker acknowledges the potential societal impact of AI replacing jobs, but maintains that code is a superior form of expression.

Transcripts

00:00

It's time to get a bit controversial.

00:02

I don't think you should write comments in your code

00:04

pretty much most of the time.

00:11

Here,

00:11

we have some code where we expect the value to be 5

00:15

Looking at this code, it's not obvious what five signals.

00:19

We could add a comment explaining what five is,

00:21

but even better we can create a constant representing the variable instead.

00:26

The if statement now reads like a comment:

00:29

that we want status to be message sent.

00:32

If your code is complex enough that it warrants a comment, you should instead

00:35

see if you can simplify or refactor the code to make it better instead.

00:41

Right now, this condition is complex enough

00:43

that we add a comment explaining it, but we can simplify this

00:47

by using variables to name parts of the expression.

00:54

Now the condition reads like the comment does.

00:57

So the comment is basically redundant and can be removed.

01:01

When conditions are complex enough like this,

01:03

you could also consider moving the whole condition to its own function.

01:07

Now you don't need to decipher at all.

01:09

Types can also make comments redundant.

01:12

In C++, there's no built in memory management.

01:15

You often have a function like this where you get back a thing,

01:19

but we need to make clear who will take ownership of the thing.

01:22

Ownership, meaning the responsibility

01:24

to release the memory after everyone is done with it.

01:27

In older C++, you pretty much had to rely on comments to do this.

01:31

If you were given ownership of an object, you'd find out by reading

01:35

the comments of the function.

01:37

But C++ added a new type called unique_ptr.

01:41

The type represents a unique reference to the object.

01:45

So if you get one, congratulations!

01:48

It's now your responsibility.

01:51

The type tells you explicitly

01:52

that you now own it without the need for a comment.

01:56

And even better, the type makes it so you get a compile error

02:00

if you do bad things with it.

02:02

A comment doesn't do that.

02:05

Likewise, if we have a function that returns an int,

02:08

but that int is optional.

02:10

We could add a comment saying that -1 means we're not actually

02:14

returning a value.

02:16

But even better, we could use a type.

02:18

If we return an optional int instead, it's

02:21

now obvious that we might not give a value.

02:24

We can't miss the comment and not realize that we might get

02:27

an invalid timestamp back.

02:29

The user needs to handle a missing value or they'll get a compiler error.

02:33

You might

02:33

wonder why don't we just make our code high quality and add comments anyways?

02:37

Isn't more comments just better?

02:40

That ignores the problems with comments.

02:42

Comments get bugs like code.

02:44

When people make changes to code,

02:45

they often don't update the comments to match.

02:48

But unlike comments, we have tools to stop bugs from entering code.

02:52

We have tests, compiler checks and limiting.

02:54

We don't have any system like that for comments.

02:57

Maybe one day we can have some static analysis tool that uses AI to determine

03:01

if the code matches the comments and flags any discrepancies -

03:04

there's a start up idea - but because of this I don't trust the comments

03:08

even when they exist.

03:10

Comments can lie, but code cannot.

03:12

So when trying to understand what a piece of code does, I read the code.

03:15

I never read the comments.

03:17

Maybe it's just me.

03:18

Do you guys find yourself reading comments to understand code?

03:22

What I do read is code documentation.

03:26

Code documentation describes the high level

03:28

architecture and public APIs of a system.

03:31

Code documentation differs from comments

03:33

where comments describe the internals of how your code works.

03:37

Documentation describes how you use the code.

03:42

The world needs more high quality documentation,

03:45

and while we could write the documentation for our code

03:48

completely separated from our code, it makes sense to keep our documentation

03:52

as close to the code as possible in order to try to help them stay in sync.

03:56

Tools like Doxygen, pydoc and JavaDoc generate documents

04:00

directly from code files and therefore change alongside our code.

04:05

It's useful to document what a class or API represents

04:08

and any expectations for interface definitions

04:11

like thread safety, possible states or error conditions.

04:15

This helps the consumers of the API know how to use it and also helps

04:18

any new implementers of the interface

04:21

know how they're supposed to operate and behave.

04:24

The guidance I've given about comments still applies for documentation.

04:27

If we write better APIs, our documentation will be more concise

04:31

and less prone to errors.

04:32

But I concede that you'll never be able to make all of the parts

04:35

of the system obvious with pure code.

04:38

I do think there's a few cases where you should consider comments:

04:41

if the code does something non-obvious for performance reasons,

04:45

a comment can help explain why the code looks weird.

04:49

If the code is utilizing a specific

04:51

mathematical principle or an algorithm from a particular source

04:54

you might consider linking to the source to help future maintainers.

04:59

There's this comic called comic strip,

05:01

and one of the comics is about a guy

05:05

telling a developer that one day we won't need code in the future

05:08

because you'll be able to

05:09

simply write a spec and the program will just write itself.

05:13

The developers are casting retorts that code is just a more precise way

05:17

of writing a spec.

05:18

I mean, I think it's wrong. And A.I.

05:21

is coming for all our jobs, and we should be afraid

05:23

of the impending sociopolitical turmoil that comes when our best tool

05:25

for distributing wealth, the job disappears.

05:28

But alas, it still helps my point.

05:31

Code is a much better way to express intent than comments about code.

05:36

So in general, if you feel like you need human language to describe your code,

05:40

see if you could make your code more human.

05:45

What other cases do you think comments are needed?

Rate This
β˜…
β˜…
β˜…
β˜…
β˜…

5.0 / 5 (0 votes)

Related Tags
CodeCommentingSoftwareMaintenanceCodeClarityTypeSafetyDocumentationAPIDesignProgrammingBestPracticesCodeVersusCommentsMaintainabilitySoftwareEngineering