I never decided on what the best way is to comment if-then-else
constructs, so I never standardized on a consistent way to comment them. I appreciate any insights.
Some options:
a)
if (blabla) { // this comment explains what happens in the IF case dothis(); } else { // this comment explains what happens in the ELSE case dosomethingelse(); }
drawback: in case of multiple dothis() statements, I like to comment the major blocks, and in that case it isn't always clear if the IF-comment belongs to the first dothis() block or to the whole IF case
or b)
if (blabla) { // this comment explains what happens in the IF case dothis(); } else { // this comment explains what happens in the ELSE case dosomethingelse(); }
drawback: only works for short comments. I usually comment IF-THEN-ELSE constructs if the IF and ELSE case isn't directly clear from the code, which typically requires a comment longer than one line.
or c)
// if the following happens if (blabla) { // then do this dothis(); } else { // or else do this dosomethingelse(); }
PS: I know about "the code should be self explanatory", but this isn't always the case...
Primarily, a single "block" comment should be placed at the top of the function (or file) and describe the purpose the code and any algorithms used to accomplish the goal. In-line comments should be used sparingly, only where the code is not "self-documenting".
If the condition inside the parentheses evaluates to true , the code inside the if block will execute. However, if that condition evaluates to false , the code inside the else block will execute. The else keyword is the solution for when the if condition is false and the code inside the if block doesn't run.
Conditional Statements Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.
if then else statement The most basic conditional construct in a programming language, allowing selection between two alternatives, dependent on the truth or falsity of a given condition. Most languages also provide an if … then construct to allow conditional execution of a single statement or group of statements.
For me, a comment above the IF
explains the IF
statement itself. For example, if the condition being tested is particularly complex.
A comment in the block below the IF
or ELSE
describes what's going once the condition has been evaluated and a choice made.
So like this:
//Is this a favoured customer and do we have a promotion? if customer.special() and monthly.hasOffer() { //Add discount invoice.addDiscount(); } else { //Add note about favoured customer scheme invoice.addNotes(JOIN_OUR_DISCOUNT_SCHEME); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With