The Elements of Programming Style

Last updated

The Elements of Programming Style.jpg
Cover of the second edition
Author Brian W. Kernighan and P. J. Plauger
PublishedMcGraw-Hill
Publication date
1978
Pages168 pages
ISBN 978-0070342071

The Elements of Programming Style, by Brian W. Kernighan and P. J. Plauger, is a study of programming style, advocating the notion that computer programs should be written not only to satisfy the compiler or personal programming "style", but also for "readability" by humans, specifically software maintenance engineers, programmers and technical writers. It was originally published in 1974.

Contents

The book pays explicit homage, in title and tone, to The Elements of Style , by Strunk & White and is considered a practical template promoting Edsger Dijkstra's structured programming discussions. It has been influential and has spawned a series of similar texts 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 book is built on short examples from actual, published programs in programming textbooks. This results in a practical treatment rather than an abstract or academic discussion. The style is diplomatic and generally sympathetic in its criticism, and unabashedly honest as well 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).

Lessons

Its lessons are summarized at the end of each section in pithy maxims, such as "Let the machine do the dirty work":

  1. Write clearly — don't be too clever.
  2. Say what you mean, simply and directly.
  3. Use library functions whenever feasible.
  4. Avoid too many temporary variables.
  5. Write clearly — don't sacrifice clarity for efficiency.
  6. Let the machine do the dirty work.
  7. Replace repetitive expressions by calls to common functions.
  8. Parenthesize to avoid ambiguity.
  9. Choose variable names that won't be confused.
  10. Avoid unnecessary branches.
  11. If a logical expression is hard to understand, try transforming it.
  12. Choose a data representation that makes the program simple.
  13. Write first in easy-to-understand pseudo language; then translate into whatever language you have to use.
  14. Modularize. Use procedures and functions.
  15. Avoid gotos completely if you can keep the program readable.
  16. Don't patch bad code — rewrite it.
  17. Write and test a big program in small pieces.
  18. Use recursive procedures for recursively-defined data structures.
  19. Test input for plausibility and validity.
  20. Make sure input doesn't violate the limits of the program.
  21. Terminate input by end-of-file marker, not by count.
  22. Identify bad input; recover if possible.
  23. Make input easy to prepare and output self-explanatory.
  24. Use uniform input formats.
  25. Make input easy to proofread.
  26. Use self-identifying input. Allow defaults. Echo both on output.
  27. Make sure all variables are initialized before use.
  28. Don't stop at one bug.
  29. Use debugging compilers.
  30. Watch out for off-by-one errors.
  31. Take care to branch the right way on equality.
  32. Be careful if a loop exits to the same place from the middle and the bottom.
  33. Make sure your code does "nothing" gracefully.
  34. Test programs at their boundary values.
  35. Check some answers by hand.
  36. 10.0 times 0.1 is hardly ever 1.0.
  37. 7/8 is zero while 7.0/8.0 is not zero.
  38. Don't compare floating point numbers solely for equality.
  39. Make it right before you make it faster.
  40. Make it fail-safe before you make it faster.
  41. Make it clear before you make it faster.
  42. Don't sacrifice clarity for small gains in efficiency.
  43. Let your compiler do the simple optimizations.
  44. Don't strain to re-use code; reorganize instead.
  45. Make sure special cases are truly special.
  46. Keep it simple to make it faster.
  47. Don't diddle code to make it faster — find a better algorithm.
  48. Instrument your programs. Measure before making efficiency changes.
  49. Make sure comments and code agree.
  50. Don't just echo the code with comments — make every comment count.
  51. Don't comment bad code — rewrite it.
  52. Use variable names that mean something.
  53. Use statement labels that mean something.
  54. Format a program to help the reader understand it.
  55. Document your data layouts.
  56. Don't over-comment


Modern readers may find it a shortcoming that its examples use older procedural programming languages (Fortran and PL/I) which are quite different from those popular today. Few of today's popular languages had been invented when this book was written. However, many of the book's points that generally concern stylistic and structural issues transcend the details of particular languages.

Reception

Kilobaud Microcomputing stated that "If you intend to write programs to be used by other people, then you should read this book. If you expect to become a professional programmer, this book is mandatory reading". [1]

Related Research Articles

AWK (awk) is a domain-specific language designed for text processing and typically used as a data extraction and reporting tool. Like sed and grep, it is a filter, and is a standard feature of most Unix-like operating systems.

Brian Kernighan Canadian computer scientist, one of the creators of Unix

Brian Wilson Kernighan is a Canadian computer scientist.

Brainfuck is an esoteric programming language created in 1993 by Urban Müller.

C (programming language) General-purpose programming language

C is a general-purpose, procedural computer programming language supporting structured programming, lexical variable scope, and recursion, with a static type system. By design, C provides constructs that map efficiently to typical machine instructions. It has found lasting use in applications previously coded in assembly language. Such applications include operating systems and various application software for computer architectures that range from supercomputers to PLCs and embedded systems.

A "Hello, World!" program generally is a computer program that outputs or displays the message "Hello, World!". Such a program is very simple in most programming languages, and is often used to illustrate the basic syntax of a programming language. It is often the first program written by people learning to code. It can also be used as a sanity test to make sure that a computer language is correctly installed, and that the operator understands how to use it.

In programming language theory, lazy evaluation, or call-by-need, is an evaluation strategy which delays the evaluation of an expression until its value is needed and which also avoids repeated evaluations (sharing). The sharing can reduce the running time of certain functions by an exponential factor over other non-strict evaluation strategies, such as call-by-name, which repeatedly evaluate the same function, blindly, regardless whether the function can be memoized.

Recursion Process of repeating items in a self-similar way

Recursion occurs when a thing is defined in terms of itself or of its type. Recursion is used in a variety of disciplines ranging from linguistics to logic. The most common application of recursion is in mathematics and computer science, where a function being defined is applied within its own definition. While this apparently defines an infinite number of instances, it is often done in such a way that no infinite loop or infinite chain of references can occur.

C++ General-purpose programming language

C++ is a general-purpose programming language created by Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significantly over time, and modern C++ now has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation. It is almost always implemented as a compiled language, and many vendors provide C++ compilers, including the Free Software Foundation, LLVM, Microsoft, Intel, Oracle, and IBM, so it is available on many platforms.

Unix philosophy Philosophy on developing software

The Unix philosophy, originated by Ken Thompson, is a set of cultural norms and philosophical approaches to minimalist, modular software development. It is based on the experience of leading developers of the Unix operating system. Early Unix developers were important in bringing the concepts of modularity and reusability into software engineering practice, spawning a "software tools" movement. Over time, the leading developers of Unix established a set of cultural norms for developing software; these norms became as important and influential as the technology of Unix itself; this has been termed the "Unix philosophy."

In computer programming, an indentation style is a convention governing the indentation of blocks of code to convey program structure. This article largely addresses the free-form languages, such as C and its descendants, but can be applied to most other programming languages, where whitespace is otherwise insignificant. Indentation style is only one aspect of programming style.

A programming tool or software development tool is a computer program that software developers use to create, debug, maintain, or otherwise support other programs and applications. The term usually refers to relatively simple programs, that can be combined together to accomplish a task, much as one might use multiple hands to fix a physical object. The most basic tools are a source code editor and a compiler or interpreter, which are used ubiquitously and continuously. Other tools are used more or less depending on the language, development methodology, and individual engineer, often used for a discrete task, like a debugger or profiler. Tools may be discrete programs, executed separately – often from the command line – or may be parts of a single large program, called an integrated development environment (IDE). In many cases, particularly for simpler use, simple ad hoc techniques are used instead of a tool, such as print debugging instead of using a debugger, manual timing instead of a profiler, or tracking bugs in a text file or spreadsheet instead of a bug tracking system.

<i>The C Programming Language</i> Programming book written by Brian Kernighan and Dennis Ritchie

The C Programming Language is a computer programming book written by Brian Kernighan and Dennis Ritchie, the latter of whom originally designed and implemented the language, as well as co-designed the Unix operating system with which development of the language was closely intertwined. The book was central to the development and popularization of the C programming language and is still widely read and used today. Because the book was co-authored by the original language designer, and because the first edition of the book served for many years as the de facto standard for the language, the book was regarded by many to be the authoritative reference on C.

Ratfor is a programming language implemented as a preprocessor for Fortran 66. It provides modern control structures, unavailable in Fortran 66, to replace GOTOs and statement numbers.

Stack-oriented programming or stack-based programming, is a programming paradigm which relies on a stack machine model for passing parameters. Stack-oriented languages operate on one or more stacks, each of which may serve a different purpose. Programming constructs in other programming languages need to be modified for use in a stack-oriented system. Some stack-oriented languages operate in postfix or Reverse Polish notation. Any arguments or parameters for a command are stated before that command. For example, postfix notation would be written 2, 3, multiply instead of multiply, 2, 3, or 2 multiply 3. The programming languages Forth, RPL, PostScript, BibTeX style design language and many assembly languages fit this paradigm.

Phillip JamesPlauger is an author, entrepreneur and computer programmer. He has written and co-written articles and books about programming style, software tools, and the C programming language, as well as works of science fiction.

In computer programming languages, a switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via search and map.

Quicksort A divide and conquer sorting algorithm

Quicksort is an in-place sorting algorithm. Developed by British computer scientist Tony Hoare in 1959 and published in 1961, it is still a commonly used algorithm for sorting. When implemented well, it can be somewhat faster than merge sort and about two or three times faster than heapsort.

Recursion (computer science) Use of functions that call themselves

In computer science, recursion is a method of solving a problem where the solution depends on solutions to smaller instances of the same problem. Such problems can generally be solved by iteration, but this needs to identify and index the smaller instances at programming time. Recursion solves such recursive problems by using functions that call themselves from within their own code. The approach can be applied to many types of problems, and recursion is one of the central ideas of computer science.

The power of recursion evidently lies in the possibility of defining an infinite set of objects by a finite statement. In the same manner, an infinite number of computations can be described by a finite recursive program, even if this program contains no explicit repetitions.

The Mouse programming language is a small computer programming language developed by Dr. Peter Grogono in the late 1970s and early 1980s. It was developed as an extension of an earlier language called MUSYS, which was used to control digital and analog devices in an electronic music studio.

Comment (computer programming)

In computer programming, a comment is a programmer-readable explanation or annotation in the source code of a computer program. They are added with the purpose of making the source code easier for humans to understand, and are generally ignored by compilers and interpreters. The syntax of comments in various programming languages varies considerably.

References

  1. Reeves, Jack W. (January 1980). "The Elements of Programming Style". Kilobaud Microcomputing. p. 9. Retrieved 23 June 2014.