
|
The Elements of Programming Style
by Brian W. Kernighan and P.J. Plauger
|
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:
- Say what you mean, simply and directly.
- Use the "telephone test'' for readability.
- Write clearly - don't be too clever.
- Don't use conditional expressions as a substitute for a logical
expression.
- Parenthesize to avoid ambiguity.
- Each time you make a test, do something.
- Follow each decision as closely as possible with its associated
action.
- Use the good features of a language; avoid the bad ones.
- Capture regularity in control flow, irregularity in data.
- Each module should do one thing well.
- Make sure comments and code agree.
- Don't just echo the code with comments - make every comment count.
- Don't comment bad code - rewrite it.
- Use symbolic constants for magic numbers.
- Watch out for side effects and order of evaluation.
- Macros are not functions.
- Watch out for off-by-one errors.
- Test programs at their boundaries.
- Program defensively.
- Make sure input cannot violate the limits of the program.
- Make it right before you make it faster.
- Keep it right when you make it faster.
- Don't sacrifice clarity for small gains in ``efficiency.''
- 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.
Amazon.comStill 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:
- Enable compiler warnings and pay attention to them.
- Use assertions to validate your assumptions.
- Don't quietly ignore error conditions or invalid input.
- For a complicated, critical algorithm, consider using a second
algorithm to validate the first. (e.g. validate binary search with
a linear search).
- 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).
- Check boundary conditions carefully.
- Avoid risky language idioms.
- Write code for the "average" programmer. Don't make the "average"
programmer reach for a reference manual to understand your code.
- Fix bugs now, not later.
- There are no free features; don't allow needless flexibility
(like realloc).
- Ultimately the developer is responsible for finding bugs; he
shouldn't write sloppy code and hope that QA will find all his bugs.
harvard.edu
[PDF]
J Nagler - PS: Political Science and Politics, 1995 - jstor.org
- "Make sure your code 'does nothing' gracefully."
- "Let the machine do the dirty work. "
- "Choose a data representation that makes the program simple."
- "Let the data structure the program."
- "Where there are two bugs, there is likely to be a third."
- "Take care to branch the right way on equality. "
- "Test input for validity and plausibility."
- "Don't patch bad code - rewrite it."
- "Don't stop with your first draft."
- "Make it right before you make it fast. Make it clear before you
make it faster. Keep it right when you make it faster."
- "Make your programs read from top to bottom."
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
- Use Lint (Less needed today but if you have it...) or Static
Analysis
- Care with Null Pointers.
- Cast away Potential Problems
- Publish Library Function Headers
- Check Array Bounds
6-10 are on Page Two
- Always Check Return Error Codes
- Don't reinvent the Wheel
- Write Clearly Not Cleverly
- Make Identifiers Unique in the first 6 Characters
- Avoid Lack of Portability
Programming Style
Examples and Counterexamples BW Kernighan, PJ Plauger - ACM Computing
Surveys (CSUR), 1974 - portal.acm.org
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.
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,
- What is your programming language of choice?
Alef
- What is your favorite operating system?
Plan 9
- Do you have a hero or role model?
I follow my nephew's advice. He advises me that Power Rangers
are getting tired..
- What is your favorite kind of music?
That which is is just past the earliest of its kind.
- What is your favorite news group?
They are pretty much all the same.
- What is your favorite web page (besides geekchic!)?
http://www.cen.uiuc.edu/cgi-bin/ryl (now broken, sorry!)
- What sports do you enjoy?
Mouth-breathing
- What kind of car do you drive?
1985 VW GTI
- What hobbies do you enjoy outside of work?
Brooding
- What is your favorite book (or author)?
S. J. Perelman
- What is your favorite movie?
Dr. Strangelove, or: How I Learned to Stop Worrying and
Love the Bomb
- What sort of clothing do you usually wear to work?
Black jeans, shirt with collar
- What is your favorite food?
My own
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:
- The statements, views and opinions presented on
this web page are those of the author and are not endorsed by, nor do they necessarily
reflect, the opinions of the author present and former employers, SDNP or any other
organization the author may be associated with.
- We do not warrant the correctness of the information provided or its fitness for any purpose
Last modified:
April 19, 2010