Comments: A deodorant to mask code smells

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() {
  ... 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.
December 04, 2013


Popular Posts

What is a Database Proxy?

A proxy is a server software, typically installed in a separate machine, that …

ChatGPT as a MariaDB database

ChatGPT is truly impressive. You can instruct it to do all sorts of things whe…

Building a Kubernetes cluster on Raspberry Pi (with automation)

Some months ago, I was lucky enough to get a bunch of Raspberry Pi minicompute…

Recent Comments

Contact Me