How do I comment the code I wrote for a course I am lecturing in?

I think the Linux kernel is a good standard.

In general, don't explain what are you doing, that should be obvious from the code. Do tell why you are doing it. Let me show an example:

data_padded = pad_with_zeroes(data, 2**ceil(log2(len(data))))
fft(data_padded)

Everybody can see that I am padding it with zeroes, and any engineer student should see I am doing it to the next power of two (modulo bugs). But they may not be aware why are you doing it: a comment should point out that a FFT is fastest when the input length is a power of two.

Also, since this is a very technical setting, add the full names of the algorithms, with alternative names if they are common, and at least a reference using the same definition as you are. Tracking down factors of 2 π can be a pain.


This is not a standard, but these are some considerations that have helped me:

If I give code for students I take special care to be consistent (I am not always successful). Students tend to find inconsistencies and think there must be a reason for that and start looking for reasons where none exist.

I also consider the purpose of the snippet: is it an example of best practice or an illustration of how such code works. In the former case I would be less verbose with my comments then in the latter case.

Sometimes it helps to have a list of trivial tricks separate from the example code. Here is an example I have used. This can be an alternative to commenting tricks in your code that are not central to the point you want to make with that example.


The same way you would comment this if writing it professionally -- unless you really think you're doing something too obscure for the students to follow after you've pointed it out.

Tags:

Code

Teaching