As I leafed through a book on Swedish grammar, I thought about refactoring, and how it’s like rephrasing text. Rephrasing doesn’t change what you say, but can be done to clarify so that others will understand you better, with less effort. A very long sentence can, especially with bad punctuation, be very demanding of the reader. So you can split it into several sentences, or introduce commas here and there, or rearrange words. It still says the same thing, only better.
Most code will be read after having been written – either before changes are made, or by some new team member who’s trying to get a grip of what the system does – not to mention when trying to find bugs, when it’s really important that code is readable.
I never liked grammar at school, but now it’s very interesting. From reading a few pages about it, I suddenly have a vocabulary for thinking about the structure of words, sentences, and paragraphs. Usually, I’ll keep rephrasing sentences that just feel wrong, until they feel right, but knowing how to classify the parts of sentences – their syntax – reveals what it is that is wrong, and which rephrasings are appropriate.
The catalog of “code smells” in the book Refactoring is a beginning to a “grammar” for code. Code smells are very good for teaching good design, I think, but we need to identify more of them. Code smells should, I think, also point out such things as doing several different things in the same statement; ordering statements “non-linearly” (when they could be ordered, “first do a, then b, and finally c“); not grouping statements that belong together; and so on.