Softpanorama

May the source be with you, but remember the KISS principle ;-)
Home Switchboard Unix Administration Red Hat TCP/IP Networks Neoliberalism Toxic Managers
(slightly skeptical) Educational society promoting "Back to basics" movement against IT overcomplexity and  bastardization of classic Unix

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

News

Classic Books

Recommended Links

Social Problem in Enterprise Unix Administration

The Unix Hater’s Handbook

 The Peter Principle

Nineteen Eighty-Four

Parkinson Law

How to Solve It

The Art of Computer Programming

The Mythical Man-Month

The Jargon file

The Good Soldier Svejk

The Power Elite

Programming Pearls The True Believer Lions' Commentary on Unix K&R Book Rapid Development Winner-Take-All Politics Military Incompetence
Alice's Adventures in Wonderland Tao of programming AWK book Animal Farm The Elements of Programming Style Humor Etc

This book written by Brian W. Kernighan and P. J. Plauger is one of the first studies of programming style. It advocates the notion that computer programs should be written not so much to satisfy the compiler or personal programming "style", but also should strive for general "readability" and "understandability" by humans with the specific goal to make software maintenance easier.

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's title and tone is a based on famous The Elements of Style, by Strunk & White . It has spawned multiple imitations tailored to individual languages, such as "The Elements of C Programming Style", "The Elements of C# Style", "The Elements of Java(TM) Style", "The Elements of MATLAB Style", etc.

The main content of the book is discussion of "short and wrong" examples from published at the time programming textbooks. This makes the book more interesting and more practical, as abstract preaching soon generates opposite reaction from the one intended.

The style is diplomatic and generally sympathetic in its criticism, - some of the examples with which it finds fault are from the authors' own work (one example in the second edition is from the first edition).

The book 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.


Top Visited
Switchboard
Latest
Past week
Past month

NEWS CONTENTS

Old News ;-)

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

[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 [email protected]. 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

B. W. Kernighan and P. J. Plauger, The Elements of Programming Style, McGraw-Hill, New York, 1974. ISBN 0-07-034199-0

B. W. Kernighan and P. J. Plauger, The Elements of Programming Style 2nd Edition, McGraw Hill, New York, 1978. ISBN 0-07-034207-5

J. Plauger selected quotes from The Elements of Programming Style

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.

Random Findings

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,



Etc

Society

Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy

Quotes

War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes

Bulletin:

Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law

History:

Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

Classic books:

The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater’s Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

Most popular humor pages:

Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

The Last but not Least Technology is dominated by two types of people: those who understand what they do not manage and those who manage what they do not understand ~Archibald Putt. Ph.D


Copyright © 1996-2021 by Softpanorama Society. www.softpanorama.org was initially created as a service to the (now defunct) UN Sustainable Development Networking Programme (SDNP) without any remuneration. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

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...

You can use PayPal to to buy a cup of coffee for authors of this site

Disclaimer:

The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the Softpanorama society. We do not warrant the correctness of the information provided or its fitness for any purpose. The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

Last modified: March, 12, 2019