Code shouldn’t need an explanation.

Sometimes comments are a red flag.

When a block of code is so complex that it needs comments to explain what it does, that is a sure sign that the code itself is too complex to stand as is.

This isn’t to say that all comments are bad. Some comments that explain why a method exists or provide some of the history as to what brought this method about are good things to have here.

It’s just when you start writing paragraphs that explain what the code is actually doing that things have gone wrong. First of all, you run the danger of the comments and the code falling out of synch, as code changes over time, and sometimes people forget to update the comments.

But the primary concern with comments that explain the code is that it’s a huge red flag that the code is too complicated to begin with. A method should be short. It should do only one thing. The variables / objects should have names from the business domain. If you follow these, it’s hard to imagine a case where you would need comments to explain the logic.

So when you see a 100-line method with 50 lines of comments that explain how it works, you really should refactor that method in the much smaller chunks. Always prefer simplicity over complexity. It’s fine for a class to have dozens of methods.

If the casual reader can understand at a glance what your code is doing and no comments are necessary, then you’ve managed to get your code to the right place.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: