Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I apply the DRY principle to commenting? [closed]

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?

like image 577
M. Slomski Avatar asked Feb 05 '23 10:02

M. Slomski


1 Answers

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*
}
like image 109
Ted Avatar answered Feb 08 '23 12:02

Ted