One of the most common questions asked by novice programmers is “How many comments should I add?”. Commenting is as much common sense than anything else. But how many comments are too many? In the following legacy Fortran program, which calculate the Factorial, n!, consider how many comments exist which don’t need to be there, primarily because they are self-explained by the code itself.
PROGRAM FACTORIAL C THIS PROGRAM CALCULATES A FACTORIAL, N! INTEGER N,M,FACT READ(*,*) N C CHECK IF N IS LESS THAN ZERO, PRINT ERROR AND TERMINATE IF (N .LT. 0) THEN WRITE(*,*) N, " IS NEGATIVE" STOP END IF C CHECK IF N IS EQUAL TO ZERO, PRINT 1 AND TERMINATE IF (N .EQ. 0) THEN WRITE(*,*) "FACTORIAL = 1" STOP END IF C CHECK IF N IS GREATER THAN 15, PRINT ERROR AND TERMINATE IF (N .GT. 15) THEN WRITE(*,*) N, " IS GREATER THAN 15" STOP END IF C CALCULATE THE FACTORIAL BACKWARDS FROM N C ASSIGN N TO FACT FACT = N C ASSIGN N TO M, THE VARIABLE WHICH DECREASES N->1 M = N C DETERMINE IF M IS LESS THAN OR EQUAL TO 1, IF TRUE JUMP TO LABEL 10 5 IF (M .LE. 1) GOTO 10 C DECREMENT M M = M - 1 C CALCULATE THE FACTORIAL FACT = FACT * M C JUMP TO LABEL 5 GOTO 5 C PRINT OUT THE VALUE OF THE FACTORIAL AND TERMINATE 10 WRITE(*,*) "FACTORIAL = ", FACT STOP END
Most of the comments, marked in red, are not really necessary. Below is the program, reengineered into a modern rendition with enough comments for the reader to understand what is happening. Half the original program dealt with outlier values of n – these have been condensed into a single statement. The goto statements, which were used to create a looping structure, have been replaced by a do loop. The statements are self-explanatory, and for the most part do not need a comment.
! This program calculates a factorial, n!: n x (n-1) x (n-2) x ... x 1 program factorial integer :: n,m,fact read(*,*) n ! Check the value of n, and terminate if not valid if (n .lt. 0 .or. n .gt. 15) then write(*,*) n, " is not in the bounds 0..15" stop end if ! If n=0, then 0!=1, else calculate n! backwards from n->2 if (n .eq. 0) then fact = 1 else fact = n do m = n-1,2,-1 fact = fact * m end do end if write(*,*) "factorial = ", fact end