1. 16
  1.  

  2. 5

    A property in comments I strive toward is that comments should describe the why, not the what. If your code is self-documenting, the “what” should be relatively straightforward. The “why”, however, is much harder to divine weeks, months, and years after the initial code was written.

    This is especially important as it relates to business logic, since many times there’s not a clear “why” to it. Sometimes, “Because FooCorp didn’t like the default backoff increment” is an arbitrary, but necessary, thing to remember when refactoring code at a later date.

    1. 4

      Based on the title, and having worked with people claiming to write “self-documenting code” who blatantly didn’t, I read this article expecting to hate it; but was surprised to came out on the other side rather liking it.

      1. 2

        A quick thing to note: several of the author’s solutions involve refactoring simple constructs like if..else clauses into functions. In C you can inline the functions, but in Python you will incur overhead for them. I also think this increases code complexity (unless that particular if .. else form is repeatedly used throughout the code). In such cases I think it makes more sense to do the traditional thing and add a comment to the block if you can’t self-document by choosing appropriate variable names and you feel that the block takes a while to decipher in the larger context of the code.

        1. 4

          Yep. Extracting the condition into a function makes sense if you’re going to be reusing it. But if not, just giving an explicit name to the condition is probably better.

          var visible = el.offsetWidth && el.offsetHeight;
          if (!visible) { }
          
        2. 1

          Giving variables and functions good names is a good thing but …

          Extracting functions: Move code into functions to clarify purpose

          Well, if this is done only for documentation purposes, it seems like you’ve just made what you are doing more difficult to find.

          If I have a nine-line function, I could divide into three sections and use a short phrase to designate each and have the whole process pretty clear. I could spend more effort, divide it into three functions and have it just as likely that the function names go stale as it is that the comment lines go stale - even through QtCreator lets me instant change function and variable name. Even worse, having the body of each function separate makes it harder to see what’s happening, change what’s happening, combine the nine lines to make just four or use a local variable to obtain some other desirable effect.

          Edit: I recall Steve McConnell in Code Complete notes that bugs tend to be found overly long functions and very short function. It seems reasonable to keep your functions medium-sized if possible and separate out the smallest subgroup with either short comment or just separating code with blank lines.