Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Well, since this is about comments and code, let's look at some actual code. Compare this typical code:</p> <pre><code>float a, b, c; a=9.81; b=5; c= .5*a*(b^2); </code></pre> <p>To this self-documenting code, which shows <em>what</em> is being done:</p> <pre><code>const float gravitationalForce = 9.81; float timeInSeconds = 5; float displacement = (1 / 2) * gravitationalForce * (timeInSeconds ^ 2) </code></pre> <p>And then to this documented code, which better explains <em>why</em> it is being done:</p> <pre><code>/* compute displacement with Newton's equation x = vₒt + ½at² */ const float gravitationalForce = 9.81; float timeInSeconds = 5; float displacement = (1 / 2) * gravitationalForce * (timeInSeconds ^ 2) </code></pre> <p>And the final version of <em>code as documentation</em> with zero comments needed:</p> <pre class="lang-java prettyprint-override"><code>float computeDisplacement(float timeInSeconds) { const float gravitationalForce = 9.81; float displacement = (1 / 2) * gravitationalForce * (timeInSeconds ^ 2) return displacement; } </code></pre> <p>Here's an example of a poor commenting style:</p> <pre><code>const float a = 9.81; //gravitational force float b = 5; //time in seconds float c = (1/2)*a*(b^2) //multiply the time and gravity together to get displacement. </code></pre> <p>In the last example, comments are used when variables should have been descriptively named instead, and the results of an operation are summarized when we can clearly see what the operation is. I would prefer the self-documented second example to this any day, and perhaps that is what your friend is talking about when he says self-documented code.</p> <p>I would say that it depends on the context of what you are doing. To me, the self-documented code is probably sufficient in this case, but a comment detailing the methodology behind what is behind done (in this example, the equation) is also useful.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload