Is it appropriate to add explanatory code?


This isn’t a question specifically tied to rust, but instead in general:
If I have a piece of code like the following:

let fps = 1. / (
            duration.as_secs() as f32 + (
                duration.subsec_nanos() as f32 / 1_000_000_000.)

but I decide to make this more efficient using some simple logic and algebra and I come out with this:

let fps = 1_000_000_000. / duration.as_nanos() as f32;

Would it be appropriate to add a comment with the prior code as an explanation, or would it be up to the reader to interpret it? In a sense I feel like the comment would be useful, but would clog up code if you don’t particularly care about small bits like this… Any opinions?

If you’re curious as to how I got to this follow through:

  1. The output of the addition is the same as the output of
duration.as_nanos() as f32 / 1_000_000_000.
  1. Since I’m dividing 1. by this result, algebra says that (if I remember correctly):
x/(a/b) =
(x/1)/(a/b) =
(x/1)*(b/a) =
//substituting x for one
1*b/a =
  1. a) and therefore we end up at the result

For elementary mathematics, statistics, etc., I suggest that no explanation is necessary, Presume that those attempting a similar task are competent in the basics of the field.

Where things are less obvious, or some special considerations (such as resistance to security side-channel attacks) is a consideration, then it’s wise to document the rationale for what otherwise looks somewhat nonsensical or unnecessary.


If you want, you can add something like this:

const NS_PER_S: f32 = 1_000_000_000.;

Then it should be obvious from the units involved in the calculation what’s going on: (ns/s)/ns.


If your using some pre computed value it can sometimes help to write the computation in a debug_assert_eq.

1 Like