DEV Community

Cover image for Refactoring 005 - Replace Comment with Function Name
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

9 1

Refactoring 005 - Replace Comment with Function Name

Comments should add value. And function names too.

TL;DR: Don't comment on what you are doing. Name what you are doing.

Problems Addressed

  • Bad Names

  • Comments

Related Code Smells

Steps

  1. Name the function with the previous comment

  2. Remove the Comment

Sample Code

Before

<?

function repl($str) {
  // Replaces with spaces the braces 

  $str = str_replace(array("\{","\}")," ",$str);
  return $str;

}
Enter fullscreen mode Exit fullscreen mode

After

<?

// 1. Name the function with the previous comment
// 2. Remove the Comment

function replaceBracesWithSpaces($input) {

  return str_replace(array("\{","\}")," ", $input);

}
Enter fullscreen mode Exit fullscreen mode

Type

[X] SemiAutomatic

Some IDEs have this refactoring although naming is not fully automatic.

Why the code is better?

Comments always lie.

It is hard to maintain comments.

On the contrary, Functions are alive and self-explanatory.

Limitations

As always, very important design decisions are valid comments.

Tags

  • Comments

See also

What is in a name?

Credits

Image by Jannik Texler from Pixabay


This article is part of the Refactoring Series.

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay