Softpanorama
May the source be with you, but remember the KISS principle ;-)

Contents Bulletin Latest Last year Top visited Scriptorama

The Elements of Programming Style
by Brian W. Kernighan and P.J. Plauger

News See also Reviews Recommended Links C History Programming style Perl Style
Programming Pearls Rapid Development Tao of programming The Mythical Man-Month Lions' Commentary on Unix Humor Etc
 

We will discuss the second edition: The Elements of Programming Style  Brian W. Kernighan, P. J. Plauger (second edition; January 1, 1978)  ISBN-10: 0070342075

The first edition was published in  in 1974, four years before the second.  This is a very small book, just 168 pages long.

The book is now is slightly outdated as Fortran examples are probably pretty foreign to most readers. Also usage "all-caps" program listings reminds of the punch cards era and is definitely  a distraction and actually oversight of the authors for the second edition. Still this book was a lasting value as a pioneer, which created the new genre of "follow-up" programming style books both generic and language-specific, for almost any language.

Among generic:

Among language specific:

The book pioneered the field of critical redesign and refactoring of the code snippets. It concentrates of micro-level, not touching more complex architectural and algorithmic issues. An  interesting detail that probably contributed to the long life of the book is that examples which they criticize and try to improve were taken from published textbooks and articles.

Authors also try to provide some generic, language independent rules and recommendations for programmers. In this area their success is mixed. Programming style is not a dogma and often textbooks with the word 'style" on the cover provide trivialities or some stupid advice.  For example advice to avoid multiple exist loops depends on the language: if the language neatly incorporates such a construct, why not use it ?

Still by-and large the discussion is pretty intelligent and authors try to avoid banalities or overgeneralization.   Programming is an art and in no way it fits any set of rigid rules. But 77 rules provided in a book can serve as a useful guideline and starting point for thinking about  "What to do and what not to do" in writing complex programs in compiled languages. Some of the recommendation are also applicable to scripting languages.

The book also contains several interesting discussions of how to transform the program to a better one and common pitfalls in programming. The authors have provided an useful set of tips for coding (and sometimes design).

Chapter 5 lists "Common Blunders" such as an un-initialized variables, too lexically close variables names (identifiers preferably should  differ by at least two letters to catch typical typing errors), etc. They point out that there is no guarantee the code will match the comments over time.

Their use of Fortran and PL/1 is regrettable (but the book is really old and C was not used much at the time), but still is hardly a problem. Outdated version of Fortran used now is a bigger 0 distraction then PL/1.  Still any competent programmer should be able to read the examples easily and understand the key idea of the examples provided.

PL/1 examples are still readable after all those years (all caps listings is just sloppiness of the authors). Actually PL/1 which fall a victim of  programming fundamentalism now can be considered to be a small, rather elegant Algol-style language :-).  From the PL/1 examples provides it is clear that the designers of C fall into the trap of oversimplification and C contains problematic areas that are absent in PL/1 (exclusion of string handing from the language was probably the main blunder -- weak string handing using the library hunts the language, too primitive preprocessor, which actually is abused/overused; unability to close multiple levels of nesting, absence of subroutines with multiple entry points, etc).  PL/1 pioneered many classic functions for dealing with strings such as index, substr and tr (the latter made its way to Unix as a utility).

The book is the source for a well known quote on writing software:  "Everyone knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, how will you ever debug it?"

Here is a summary of the important programming style tips from Brian Kernighan's 1994 guest CS50 lecture:

  1. Say what you mean, simply and directly.
  2. Use the "telephone test'' for readability.
  3. Write clearly - don't be too clever.
  4. Don't use conditional expressions as a substitute for a logical expression.
  5. Parenthesize to avoid ambiguity.
  6. Each time you make a test, do something.
  7. Follow each decision as closely as possible with its associated action.
  8. Use the good features of a language; avoid the bad ones.
  9. Capture regularity in control flow, irregularity in data.
  10. Each module should do one thing well.
  11. Make sure comments and code agree.
  12. Don't just echo the code with comments - make every comment count.
  13. Don't comment bad code - rewrite it.
  14. Use symbolic constants for magic numbers.
  15. Watch out for side effects and order of evaluation.
  16. Macros are not functions.
  17. Watch out for off-by-one errors.
  18. Test programs at their boundaries.
  19. Program defensively.
  20. Make sure input cannot violate the limits of the program.
  21. Make it right before you make it faster.
  22. Keep it right when you make it faster.
  23. Don't sacrifice clarity for small gains in ``efficiency.''
  24. Don't stop with your first draft.

As one reviewer of the book on Amazon noted:

I dare say many rules Mr. Kernighan preached almost three decades ago are still NOT followed by the programming community at large. For examples, "Modularize. Use subroutines." "Each module should do one thing well." and "Don't patch bad code--rewrite it." A widespread, bad practice of 90% of the programmers today is still writing functions that are way too long! And they very often keep modifying existing functions--inserting new logic into them--to make already bad code even worse; they seldom give it a second thought about rewriting the whole damn crap!

Another set of rules from the book: "Make sure code and comments agree." and "Don't over-comment." Many programmers seldom do the first thing, resulting in widespread mismatches between the actual codes and surrounding comments. This applies to Java code as well. The comment style recommended by Java--that is, mixing code and comments that can be extracted into so-called self documentation--is an outright violation of the "don't over-comment" rule. (This is intended to be a criticism of Java-style comments.) Good code should document itself clearly; with perhaps a little help from judiciously added few comments that are not self-evident from the code itself.

The book uses FORTRAN and PL/I code examples. There are things that no longer apply today. But the fundamental rules and styles are still well applicable today and in the future.

Old News

[Apr 19, 2010] Writing Solid Code (Microsoft Programming Series) (9781556155512) Steve Maguire Books

Amazon.com

Still Offers Good Advice, December 4, 2002

By Paul J. Mantyla (Sunnyvale, CA USA) -

This review is from: Writing Solid Code (Microsoft Programming Series) (Paperback) The negative reviews I've read tend to fall into two categories: 1) Anti-Microsoft Bashing and 2) Nitpicking.

This book isn't a recipe book, and it's a bit dated, having been written during the days of DOS and the first Macintosh, but the underlying themes and general advice are still valid:

  1. Enable compiler warnings and pay attention to them.
  2. Use assertions to validate your assumptions.
  3. Don't quietly ignore error conditions or invalid input.
  4. For a complicated, critical algorithm, consider using a second algorithm to validate the first. (e.g. validate binary search with a linear search).
  5. Don't write multi-purpose functions such as realloc (it can grow memory, shrink memory, free memory, or allocate new memory -- it does it all).
  6. Check boundary conditions carefully.
  7. Avoid risky language idioms.
  8. Write code for the "average" programmer. Don't make the "average" programmer reach for a reference manual to understand your code.
  9. Fix bugs now, not later.
  10. There are no free features; don't allow needless flexibility (like realloc).
  11. Ultimately the developer is responsible for finding bugs; he shouldn't write sloppy code and hope that QA will find all his bugs.

Coding Style and Good Computing Practices

harvard.edu [PDF]
J Nagler - PS: Political Science and Politics, 1995 - jstor.org

Software Development Quotations by P. J. Plauger

The Ten Commandments for C Programmers (Annotated Edition)

See also 10 Commandments for C Programming by Henry Spencer

These were written by Henry Spencer a programmer and engineer for the Canadian Space Agency. They are published widely on the web but as that is ephemeral are included here, I understand they are in the public domain but should that prove wrong, please notify me by email at cplus.guide@about.com. it is About.com's policy to always respect copyright.

My summary of his commandments is

  1. Use Lint (Less needed today but if you have it...) or Static Analysis
  2. Care with Null Pointers.
  3. Cast away Potential Problems
  4. Publish Library Function Headers
  5. Check Array Bounds

    6-10 are on Page Two

  6. Always Check Return Error Codes
  7. Don't reinvent the Wheel
  8. Write Clearly Not Cleverly
  9. Make Identifiers Unique in the first 6 Characters
  10. Avoid Lack of Portability

Recommended Links

The Elements of Programming Style - Wikipedia, the free encyclopedia

Programming Style Examples and Counterexamples BW Kernighan, PJ Plauger - ACM Computing Surveys (CSUR), 1974 - portal.acm.org
 

Brian Kernighan homepage

Dennis Ritchie Home Page

freshmeat.net Project details for The Elements of Programming Style - fortune cookie

The Elements of Programming Style - fortune cookie is a fortune cookie file containing the 69 tips from the "Elements of Programming Style" by Kernighan & Plaugher.

Etc

Geek Réplique Dennis Ritchie

Dennis Ritchie, renowned author of the C programming language, obligingly responded to our query as follows:
 
I don't usually answer this kind of request; various Who's Who compilers have gone unrequited. Nevertheless,

 

 



Copyright © 1996-2012 by Dr. Nikolai Bezroukov. www.softpanorama.org was created as a service to the UN Sustainable Development Networking Programme (SDNP) in the author free time. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Site uses AdSense so you need to be aware of Google privacy policy. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine. This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

Disclaimer:

Last modified: April 19, 2010