Skip to main content

Comments: A deodorant to mask code smells

·246 words·2 mins
Programming
Alejandro Duarte
Author
Alejandro Duarte
Alejandro Duarte is a Software Engineer, published author, and Developer Relations Engineer at MariaDB. He has been programming computers since the mid-90s. Starting with BASIC, Alejandro transitioned to C, C++, and Java during his academic years at the National University of Colombia. He relocated first to the UK and then to Finland to foster his involvement in the open-source industry. Alejandro is a recognized figure in Java and MariaDB circles.
Funny T-shirt for Developers

Don’t get me wrong. Comments are useful and not all of them have the olfactory purpose of the famous analogy I’m using in this article’s title. So, what’s so wrong about comments that programmers are willing to even dress a shirt about this odorous matter? Let’s say we have this fragrant method:

nastyMethod() {
  // connect to database
  ... Code to connect to the database ...

  // create default configuration
  ... Code to create the default configuration ...

  // load configuration
  ... Code to load the configuration ...

  ... and more, and more, and even more of this...
}

The problem here is that the comments are saying what the code is doing. Comments should say WHY the code is doing something, not WHAT the code is doing. Moreover, this typically leads to the Long Method anti-pattern putting in risk two basic OO design principles: Interface Segregation Principle and Single Responsibility Principle to say the less.

Make your code self explanatory:

betterMethod() {
  connectToDatabase();
  createDefaultConfiguration();
  loadConfiguration();
}

connectToDatabase() {
  ... Code to connect to the database ...
}

createDefaultConfiguration() {
  ... Code to create the default configuration ...
}

loadConfiguration() {
  ... Code to load the configuration ...
}

You might argue “this extract to method thing will lead to classes with too many methods, making them difficult to understand”. Well, use the Extract Class refactoring if you reach that point. Remember: The object oriented programs that live best and longest are those with short methods.

Enjoyed this post? I can help your team implement similar solutions—contact me to learn more.

Related

Lightning fast commenting (in and out)
·123 words·1 min
Programming
A quick trick for commenting and uncommenting code efficiently.
Empty lines and semantics in source code
·536 words·3 mins
Programming
The importance of empty lines for readability and semantics in source code.
Book Give-away: Win a free copy of the book "Vaadin 7 UI Design By Example" - Just by commenting!
·246 words·2 mins
Vaadin News
Participate in a contest to win a free copy of the book “Vaadin 7 UI Design By Example” by commenting on this post.