How can I apply the DRY principle to commenting?

165 Views Asked by At

I have multiple functions using the same complex line of code that I needed to comment.

function thisFunction() {
  [Some Code..]
  // Comment for clarification
  *complex code line*
}

function thatFunction() {
  [Some Code..]
  // Comment for clarification
  *complex code line*
}

function anotherFunction() {
  [Some Code..]
  // Comment for clarification
  *complex code line*
}

The main issue I see was having to explain for different functions the same complex code multiple times with the exact same comment.

This goes against the DRY principle. My question is, "What would be the best practice to resolve this problem and still let readers understand my code?"

My overall thought was to only comment the first usage for that complex line. However, I don't know if this would be 100% intuitive for other people if they are reading.

EDIT: For clarification, I have one line of code used in multiple functions. I don't know if I should keep the duplicated comments, comment only the first usage of the complex line, or create a helper function that each of the current functions can use even if that helper function only contains the comment and the one complex code line. Ideas?

2

There are 2 best solutions below

5
On BEST ANSWER

Encapsulate the complex code into it's own function, and provide the comments once:

function thisFunction() {
  [Some Code..]
  complexCodeFunction();
}

function thatFunction() {
  [Some Code..]
  complexCodeFunction();
}

function anotherFunction() {
  [Some Code..]
  complexCodeFunction();  
}

//comment for clarification
function complexCodeFunction(){
    *complex code*
}
1
On

In case all the lines of complex code are exactly the same, it should be possible to extract them out into a separate function:

function thisFunction() {
  [Some Code..]
  complexOperation();
}

function thatFunction() {
  [Some Code..]
  // Comment for clarification
  complexOperation();
}

function anotherFunction() {
  [Some Code..]
  complexOperation();
}

function complexOperation() {
   //comment for clarification
   *complex code line*
}

In case the complex line of code is not easily extractible or the lines differ in some key aspects, I don't think it is a problem to duplicate the comments. The DRY principle applies mainly to code itself, comments are a clarification for the developer, so that the code is more understandable. If the comments help the reader to understand the code better, there is no reason to avoid this duplication.