Skip to main content

What Can You See: A Guide (Rant) on Commenting

I occasionally find code examples online where the author, in their effort to fully communicate the breadth and detail of a proposition and solution, has commented almost every, or every single line of code.

I am not going to say that exhaustive commentary is universally opprobrious, but as sample code online, for my part, all I can do when I see this is rage close the tab and look elsewhere for examples to help me with my project. I will, however, propose that there is almost no use for the

# comment
code;
# comment
code;
...

format. The alternation is arresting to the reading of either code or commentary. The only way to get any comprehension out of this maximally irritating and interrupting layout is to slowly read each line sequentially from top to bottom and hope the author's flow of logic is perfect and simple enough to communicate the essential detail you're looking for without rereading. I suppose then this kind of commenting might make sense for beginners (to beginners?), but even then, I wouldn't expect a beginner to learn, or want to learn this way from 100+ lines of code (that is 50+ lines of comment and 50+ lines of code). One of many errors of presentation this style gives away without even reading the code (or the commentary) is that the author can't or doesn't know how to separate information on the structural and conceptual layers in the code. As a result, interspersed amongst all the comments telling you about how variables are getting initialized must go the fragmented discussion about what the code is trying to do. Everything is looked at from the perspective on the street. All you can see looking up are trees and tall buildings. There are cars driving by, but you don't know where they're coming or going, or why. You can't gauge the relative height of the buildings, or the architectural aesthetic of the trees. Civilization looks lovely and elegant from an airplane window. There is no need to agonize over street signs when you can clearly see how the roads connect. Exessive commentary would just distract the view and make you want to look away.

This reminds me of an astronomy presentation I attended a few years ago. The presenter was discussing his project's work of photographing the sky with an ultra high resolution camera. While I don't dismiss the importance of increased precision of scientific instruments, something about the approach seemed naive to me in the same way that commenting every line of code does. High precision comprehension or visibility should not set the attention to the little bits. Rather the increased resolution should feel more like a grid relaxation, as if the optics you're using to peer at the subject eventually, by refinement, itself becomes sufficiently imperceptible. Of the many wonders of nature is that much like a fractal, each scale presents a different structure. Think for a moment about photographing the sky with a multi-gigapixel camera. How far out from the earth in spacetime must you travel before each pixel contains an area larger than a galaxy? Are there galaxies visible to your camera that far out? What about the movement of the earth against an intergalactic background compared to the exposure time at that distance? If you wish to learn about a biological structure, like an ecosystem, or a plant, you don't invent an ecosystem- or plant-sized fine dicer, cut the subject into the tiniest pieces possible and then make a great deal of effort zooming in on your new collection of bits. The windowing function in this case forces such a bias that any phenomena observed must be of your own imposition.

Good commenting, like good programming, requires experience and discernment. If you really have so much to say about what your code is doing, consider a programming guide or notebook companion. Apply a rhetorical format that is appropriate for the topic. You would not discuss refinements you've made to a Fourier transform routine in the same way you would write down the shortcuts you took in a project due to business requirements. In the former case, you're complementing the code with exposition on the advantages and applicability of your enhancements vs a standard implementation. In the latter case, you're reminding the reader or yourself that a known substandard, but acceptable solution was adopted because of external constraints and that it needs to be replaced.

Most of the time effective commenting means adding comments sparingly. My rules for commenting I don't think are too much different from the standard wisdom and are slightly contradictory in their separate goals:

  1. Focus the commentary on what the code is trying to do and what deviations you may have made if any from a more conventional approach, e.g. did you have to workaround an upstream bug? Your reader already knows how source code works, so don't waste effort on describing how an if statement works. Do spend effort rephrasing an irreducible compound boolean expression in more colloquial language.
  2. Only write a comment if the block of code itself cannot summarize on its own what it is doing. Code blocks that cannot express what they are doing have limited maintainability. Sometimes this cannot be avoided if you're using an arcane language or are writing a performance sensitive or resource constrained application.
  3. If you need to comment one section of code, try to comment the other sections at a similar level to aid the reader in how the code progresses from top to bottom.
  4. Try to keep comments at the same level both indentation-wise and concept-wise. If you find that you need to mix more than a few lower- or higher-level comments in, then consider this to be a sign that your code itself spans too many structural layers and needs to be refactored such that the code block/namespace/module/class/object/function/expression in question has a well-defined scope and a more singular narrative of commentary.
  5. If your comment on one section of code is much longer than the others, or you find that you can't clearly and succinctly express what it is doing, consider this a sign that that section might need to be refactored such that its purpose is less fraught and more singular. (The reader (of this blog) is invited to think a moment at this point about Euclid's postulates and what wonderful things happened to geometry when the parallel postulate was finally resolved into a triplet state.) Cleverness is its own reward and almost never brings additional value. Code that is not maintainable is only disposable.

The Dystopia of Merit

I have long thought about the thesis of and cultured indignation against the rapidly evolving phenomena detailed in this article. I read/skim ~70 articles per day, so it is rare for me to read an entire article, but I recommend you to read this one as I have done. Normally I only have to read a few sentences or sometimes even the title and a few sentences before I can gauge the argument, tone, evidence, and novelty contained in an article, know how I will assent as much against my own worldview bias, or don't care. I have been reading the news for so long and have formed a comprehensive library of opinions and perspectives and can already reduce most articles to a few data transactions against the representative opinions. This is, however, the subject of another post.

What I have been thinking much about recently is a small portion of the meritocratic mania to reformat both economy and society into the image of a science fiction dystopia. My thoughts concentrate on two comparatively diminutive points within the scope of this dystopian realm.

The first is what I call the resume curse. Your previous work history tends to dictate the kinds of jobs prospective employers are willing to consider you for. Employers are most of the time unwilling to take or incapable of taking what they think is a risky gamble on someone without what they think is auditable experience. Stay in any one application stack or subfield too long, and you'll be asymptotically stuck to that stack or field, regardless of your as yet professionally unsubstantiated aptitudes in other areas. And should your unwittingly imposed expertise become factored out of existence, or worse, popularity by the industry, it's game over. Another hazard the resume curse creates is something like an inverted situation, wherein rather than converging you into a pigeon hole, your resume appears to present sufficiently much eclecticicity that your prospective employer characterizes your disparate tastes, or life happenstances as unfocused, undisciplined, and undependable.

The conventional wisdom here is that successful people create rather than take jobs. The probability of your next job being good or not depends on your ability to convince people that you can excel at the things you want to do. As trite as it may seem, most of the time this is achieved with some people sense and plenty of hard work.

The second scenario is complementary to the first and is called the goldilocks syndrome. Prospective employers are only willing to hire you if your experience in a handful of areas meets or exceeds their arbitrary, usually unrealistic, rubric. For example, 100+ years of C++, 25+ years of git, 15+ years of COBOL, 7+ years of go, srsly. (Also, Google has the resources to construct custom tools, libraries, even custom languages to exact more performance out of their custom technology stacks and then drop the gauntlet upon the world as open source projects. Why is it that everyone is compelled to appropriate their stuff with an inverted sense of attention to applicability?) I'm sure the comedic list of job requirements attached to most public job listings are the evidence of pandemic insecurity or ineptitude of HR departments desperate to regulate the job acquisition process in the wrong way.

The conventional wisdom is that good managers hire the best people they can find and then create a role for them rather than describe superman's exact history and sequence of errantry and then expect him to apply. (Withdrawing from the hyperbole for a moment, I imagine that what usually happens is that lazy HR grunts duplicate the toolsets and project history of the departing dev/admin at the company as the absolute verity for the job, and nothing less). The level of detail exacted often descends way down into bland detail, with strictures on shoe tying methods. Truly only superman ties his shoes correctly.

Adventures in Polyomino Tiling

Recently I began working on a recreational programming project that unites several subjects I have been wanting to explore for many years: AI, GUI programming, certain mathematical problems, and the intellectual zen and stimulus of gamifying them. My experiences with computer games growing up were quite limited despite that our family was somewhat early to install a 'family computer' in the library in 1992, a 80286 loaner at first and then a late model 386 with a turbo button on the chassis that doubled the CPU freq from only 33 to a screaming fast 66 MHz. I attribute this to my family's traditionalist values. Whether these positively or negatively curtailed my proclivities and aptitudes for computer-based labor, I cannot say for sure. It is true that I did not waste months of my youth on low quality game time, but I've never been wont for abdicating my languid and wastrel temporal habits. I recall several days or even weeks of boredom, and I am sure I have even made up some of the deficit in recent years with several offerings of temporal squandering in low grade video game time: a burning of time against the relentless scourge and depression of real adult responsibility.

Though I've never had the patience for most serious video games, nor the dedication and care to accommodate any I do find interesting with necessary computing resources--I'm insufferably opinionated over the most tedious minutiae and seem to exist in a perpetual state of annoyance even, or especially, when it comes to 'entertainment'--I do remember the halcyon days of sneakernetting copies of simulation games from my friend's house on a 3.5" floppy disk and covertly installing them on our family computer. My brother also found free demos of doom and dark forces online that have got me on a 90's retro Star Wars game tear lately, so long as they work in dosbox or wine. But I greatly digress. The topic here is polyomino games, specifically a game format that is as captivating as it is simple: tetromino tiling.

I used to play ksirtet in the KDE 3 days, but they didn't port it to QT/KDE 4 and the replacement didn't have all of the configurable keyboard shortcuts that ksirtet had. Ksirtet added two features that meaningfully enhanced the gameplay in a way that lowered the threshold for the zen state: translating pieces to the left and right sides of the board, and showing a shadow (a projection) of the piece under the bottom of of the tile board. This allowed you to maintain constant focus on the existing tiling state while simultaneously processing everything else with peripheral sight.

This is my second attempt at reimplementing ksirtet, the first devolved rapidly into vapid, desultory digressions on generalized multidimensional polyomino tiling problems and algorithms. Fortunately, now that I'm older and less idealistic--more impatient, perhaps--I've made some progress. I can't claim much so far for myself as I copied the code directly from Jan Bodnar's excellent wxPython demo tutorial, for which he also has a parallel pyQT version. I'm still evaluating whether to continue with wxPython or not. The relative elegance of the GUI framework will hopefully matter little to me and I may make a change if it results in drastically simpler cross-platform dependencies.

Screenshot of pySirtet 0.1

pySirtet 0.1 in action. Version 0.1 is basically a refactor of the zetcode demo. I've made the code more pythonic, and defintely a little more justinesque.

If you are interested in the game, you can follow the development on GitHub. I have been moderately impressed with the quality of documentation

and good information (as stackoverflow Q&A's, for example) on wxPython online so far, so I may stay with wxPython for now, despite that Phoenix hasn't molted yet.

On Learning Maths

While imagining how awesome of a maths and philosophy teacher I am going to be for my daughter, whose patience occasionally expires in expressions such as "dad, you don't have to teach me all the time", I recalled my own experience with elementary maths and how wastefully and long I fought against both the formalism and, more significantly, the threat and charge of inadequacy for miscomprehension or substandard performance--so much for meritocracy.

The first real arrival a student experiences in the primary education of mathematics in the US is elementary algebra, which is something of a sterilized and frustrating scope from the wonderfully weird and bizarre natural scape of algebra. The subject of elementary algebra is necessarily constructed from two theories: the theory of equations and the theory of functions, and typically features a myopic fixation on polynomial functions. Neither command of nor felicity in the topic can be attained without a fluent proficiency in both theories. For me, it was not until I took foundations of analysis, well into a maths BS, taught by a practicing mathematician at a research university that my understanding of these two theories was finally made clear. How much more advantage that my daughter would have then I, I thought, to learn from someone who knows the rigor and loves the subject.

There are other mathematical lexicons so fundamental to their domain, and all those that derive therefrom, similar to the theories of equations and functions, that I wish I either had had the intelligence to recognize or the fortune in a teacher wise enough to make it clear when I formally began learning them. The first comes from the theory of differential equations and the second from the theory of probability. Fluency in elementary algebra and calculus is not sufficient to be successful in constructing and applying differential equations and their solutions or appropriating their models. The same can be said about elementary algebra, some of whose ancient practitioners conjured wild scenarios to solve as if by magic. But since we are to learn that elementary algebra only has merit in the service of other topics, specifically those that form the mathematical prerequisites for a proper engineering education, no such interest or wonder was ever afforded by me to the magic of long form word problems in elementary algebra and how the application thereof is artful or captivating. A proper engineer's pursuit, however is the creative and discriminating application of differential equations, both ordinary and partial, and their solutions. Again, it was not until my second semester of graduate quantum mechanics that I think I really started to see such maths in nature. Once you learn the ways of differential equations, you never look at things in the same way again. You see them as boundary conditions, resonances, and decays.

The last item comes from the theory of probability, is more of a concept than a dialect, and is called a random variable. Like differential equations, which can be seen as a generalization of the theory of equations to which the solutions are functions rather than variables (sets), random variables generalize the meaning of a variable in ways that are profoundly insightful to any field that applies maths to reality, but a full comprehension for me only came together near the end of my first semester in undergraduate probability.

My relative travails in each topic I think demonstrates my own daft beginnings more than anything else. We know so little about ourselves in the beginning and how we learn. Mathematics has never been easy for me and despite the unrelenting contrary accusations. It is a fulfilling competence that was refined only through years of intellectual agony and determination. I think I was improbably lucky to have obtained and retained a handle on its innate, sublime beauty from when I was very young.

Maths is a language but they are also a curious collection of disparate locales with translations and orthonormal purposes as needed. Seductive formulas such as the complex exponential and elliptic curves belie an awesome variety and utility underneath their deceptively simple forms and we conjecture about yet more ambitious, unified truth from simple forms. I always return to Hilbert's defiant declaration:

Wir müssen wissen.
Wir werden wissen.

and wonder what weird meaning is wrought from raw logic in the human mind against its eclectic Condition and whether that construct really does sing the music of the universe, or the mad phantasms and sprites that spring into consciousness or both.

Setting Up Blog

I've always been wary of third party and/or hosted web publishing platforms, but it seems that there are plenty of lightweight static blogging engines out there. For me it came down to pelican and nikola, wherein I chose nikola. Mainly I wanted something that advertised full support for rST, and a few other niceties, such as tags and comments.