About this book
The Elements of Programming Style is a short book by Brian W. Kernighan and P. J. Plauger, first published by McGraw-Hill in 1974, with a revised second edition in 1978. Its title deliberately echoes The Elements of Style, the small guide to English usage by William Strunk and E. B. White that generations of students had been given to cure them of wordy, muddled prose. Kernighan and Plauger set out to do the same for programs.
The method is simple and was unusual at the time. The authors collected examples of code from published programming textbooks, the very books from which students were learning. They printed each example, explained what was wrong with it, and rewrote it. Each discussion ends with a short maxim that sums up the lesson. At the close of the book these maxims are gathered into a single list that can serve as a checklist.
Choosing textbook code was a pointed decision. The authors were not mocking beginners or careless amateurs. They were showing that code offered as a model to learners was often confusing, inefficient, or simply wrong. If the teachers wrote like this, it was no surprise that the students did. The book's quiet argument is that the field had not yet learned to value clarity, and that this was costing it dearly in errors and maintenance.
The examples are written mostly in Fortran and PL/I, the dominant languages of scientific and business computing in large organisations at the time. Some readers today find this off-putting. It need not be. The authors explain whatever syntax matters, and the reasoning behind each rewrite does not depend on the language. A reader who has never seen Fortran can follow the arguments, much as a reader of Strunk and White can follow the advice without knowing the books its examples came from.
The question the book answers is practical. What makes a program clear, and how do you turn an unclear one into a clear one? The answer is not given as a theory. It is shown, case by case, through dozens of small rewrites, until the reader begins to see code the way the authors do.
The book appeared at a turning point. The debate about structured programming was at its height, sparked by Edsger Dijkstra's 1968 letter against the unrestricted use of the goto statement. Many programmers were arguing about rules in the abstract. Kernighan and Plauger sidestepped the slogans and simply showed what disciplined code looked like, side by side with code that lacked discipline. For many readers this was more persuasive than any manifesto.
The audience was anyone who wrote programs: students, working programmers and especially teachers. The book assumes the reader can already program. It does not teach a language. It teaches judgement, the ability to look at working code and see that it could be better, and to know how to make it so.
The second edition of 1978 kept the method and the overall plan but revised the material in light of the four years since the first. Some examples were reworked and the treatment updated, reflecting the authors' further experience and the spread of structured programming ideas. Most readers today will meet the second edition, and the differences between the two do not affect the lessons a modern reader should take away.
The book is also unusually short for its influence. It can be read in a few evenings. That brevity is part of its argument. A book that pleads for clarity and economy and then runs to many hundreds of pages would undercut itself. Kernighan and Plauger practise what they recommend: every example earns its place, and no point is made twice when once will do.
The authors
Brian Kernighan was born in Toronto in 1942. He studied engineering physics at the University of Toronto and earned a doctorate in electrical engineering at Princeton. He then joined the Computing Science Research Center at Bell Labs, the group that created Unix and C. He stayed there for about three decades before moving to Princeton University as a professor of computer science.
Kernighan's name is attached to several books and tools that shaped the field. With Dennis Ritchie he wrote The C Programming Language in 1978, a short and famous book whose clarity of exposition became a model for technical writing. He co-created the AWK text-processing language with Alfred Aho and Peter Weinberger, and the K in AWK is his initial. With Rob Pike he wrote The UNIX Programming Environment in 1984 and The Practice of Programming in 1999. With Plauger he also wrote Software Tools in 1976, later reworked for Pascal, which taught how to build small, well-designed programs that work together.
A single theme runs through all of this: respect for the reader. Kernighan's books are short, plain and exact, and they treat programs as texts that must be read and understood by people. The Elements of Programming Style is the earliest and most direct statement of that theme.
P. J. Plauger, born in 1944, also worked at Bell Labs in the early 1970s. He went on to found Whitesmiths, a company that produced one of the first commercial C compilers, and later played an important part in the standardisation of C and C++, serving in leading roles in the standards committees. He wrote widely on programming, including The Standard C Library, and for years wrote columns for programming magazines. He also had a parallel life as a science fiction writer and won an award for new writers in that field in the mid-1970s.
The pairing suited the book. Both authors were working programmers in a research setting that prized simplicity, small tools and clean design. Both wrote well. And both had seen enough code from outside Bell Labs to know how far ordinary practice was from what was possible.
The shape of the argument
The book is organised by the kinds of decision a programmer makes, starting small and moving outward. It begins with the smallest units, single expressions and statements, and asks how to write them so their meaning is plain. It then widens to control flow, the arrangement of loops and conditions that decide the order in which things happen. From there it moves to the structure of whole programs, how they are divided into parts and how those parts relate.
After structure, the book turns to the edges of a program, where it meets the outside world through input and output, and to the common errors that cluster at those edges and elsewhere. It then takes up efficiency, asking when speed matters and how to find out where the time actually goes. Documentation comes near the end, and the book closes with a short reflection and the gathered list of rules.
The movement is from the line to the whole, and from the inside of a program to its boundaries with people and data. Each stage builds on the previous one. Clear expressions make clear control flow possible. Clear control flow makes clear structure possible. A clearly structured program is easier to make robust at its edges, easier to tune where tuning is needed, and needs less documentation to be understood.
The argument does not move by definitions and proofs. It moves by example and rewrite. Each case is a small story: here is a piece of code, here is what it is trying to do, here is why it is hard to see that, here is a version that says the same thing plainly, and here is the general lesson. The rules are distilled from the cases, not imposed on them. This matters, because a rule learned through a concrete case is understood, while a rule merely memorised is often misapplied.
The book is also notable for what it leaves out. It offers no grand methodology, no diagrams, no lifecycle model. It stays close to the text of programs. Its claim is that much of software quality is decided at this level, in thousands of small choices, and that a programmer who makes those choices well will avoid a great many larger problems.
A note on what the reader should bring. The book rewards patience more than background. Someone who has written a few hundred lines in any language will follow every example. Someone with decades of experience will still find cases that make them wince at their own habits. The ideal reader approaches it as a working writer approaches a style manual: not to learn the craft from scratch, but to sharpen an eye that daily work has dulled.
Clarity before cleverness
The first and governing idea of the book is that clarity comes before almost everything else. One of its best-known maxims puts it in a few words: “Write clearly — don't be too clever.” The rest of the book can be read as an elaboration of this single rule.
The reason is economic as much as aesthetic. A program is written once and read many times: by its author while debugging, by colleagues during review, by maintainers years later. Every reading costs time, and every misreading risks a new error. A clever trick that saves a line or a few microseconds may cost hours of confusion over the program's life. Clarity is therefore not a luxury added after the real work is done. It is part of what makes the program correct and cheap to keep.
Cleverness in this sense means code whose meaning depends on knowing a trick. A calculation that uses integer division to produce a side effect, a condition that relies on an obscure rule of operator precedence, a loop that does two unrelated jobs to save a pass over the data: each may work, and each forces the reader to stop and decode it. The authors show many such cases from the textbooks, and in almost every one the clear version is no slower and often shorter.
An analogy from ordinary writing helps. A sentence packed with subordinate clauses and unusual words may be correct, even impressive, but if readers have to read it three times, it has failed at its job. Good prose lets the reader attend to the meaning, not the sentence. Good code does the same. The meaning should be visible on the surface.
The idea is often confused with a demand for simplicity at any cost, or with a rejection of sophisticated algorithms. That is not what the authors mean. A complex problem may need a complex solution. The point is that the complexity should belong to the problem, not to the way the code is written. A hard algorithm written clearly is better than an easy one written obscurely.
The idea also has a moral edge, though the book states it lightly. Clever code often serves the author's wish to be admired more than the reader's need to understand. Choosing clarity is choosing to serve the reader. This links the book to the human view of programming found in Gerald Weinberg's work, which appeared a few years earlier.
Say what you mean
A second idea concerns the smallest units of code. Expressions and statements should state their intent directly. If you mean to test whether a number is negative, test that, not some roundabout condition that happens to be equivalent. If you mean to take the larger of two values, use the plainest form the language offers. The authors show again and again how textbook code reached simple results by indirect routes, and how the direct route was easier to read and harder to get wrong.
Several habits fall under this heading. Use the language's natural constructs rather than imitating them with lower-level ones. Use library functions for standard tasks instead of writing your own version of something that already exists and has been tested. Avoid temporary variables that serve no purpose except to break a computation into confusing pieces. Write conditions in positive form where possible, since a chain of negatives is hard to follow. Use parentheses to make grouping unmistakable when precedence rules might confuse the reader.
Consider an example in plain terms. A programmer wants to know whether a year is a leap year. One version tests a series of divisibility conditions in a tangle of nested branches, with flags set and reset along the way. Another version states the rule in one logical expression that mirrors the way the rule is described in words. Both give the same answers. Only the second lets a reader check it against the rule in a few seconds. The authors' rewrites are often of exactly this kind: the logic is unchanged, but its shape now matches the idea.
Naming belongs here too. A variable called by a single letter in a long routine forces the reader to remember what it holds. A variable named for its role tells the reader at every use. The book does not make a fetish of long names, but it treats names as part of saying what you mean.
This idea is sometimes confused with mere tidiness. It goes deeper. When code says what it means, errors become visible. A condition that is written directly can be checked against the specification; one written indirectly hides its mistakes. Saying what you mean is a debugging technique as much as a style.
Control flow that reads from top to bottom
The third idea concerns the order in which a program does things. The book argues that a reader should be able to follow a program's logic from top to bottom, without jumping around. Each decision should be visible where it is made, and each loop should have a clear beginning, end and purpose.
This was the practical side of the structured programming debate. Older Fortran code often used goto statements and numbered labels to direct control, so that a reader trying to follow a computation had to leap from line to line, keeping a mental map of where each jump went. Small changes could break the map in ways that were hard to see. Code written this way earned the name spaghetti, because its paths tangled like noodles on a plate.
Kernighan and Plauger do not issue a blanket ban on goto. Their approach is more practical. They show tangled examples and rewrite them using the structured forms available, such as if-then-else and well-formed loops, and the result is almost always clearer. Where a language lacked good structured forms, as early Fortran did, they show how to use what was available in a disciplined way. The lesson is about structure, not about a keyword.
Several guidelines follow from this. Choose the loop form that fits the problem, so that the loop's condition tells the reader when it ends. Avoid loops with multiple scattered exits when one clear exit will do. Use else-if chains for multi-way decisions so that each case is visible and mutually exclusive. Avoid branching to the same place from many directions. Keep the code for each decision close to the decision itself.
An analogy is a set of directions to a house. Good directions take you in order: go straight, turn left at the school, the house is third on the right. Bad directions say: go straight until step five, unless you passed the bakery, in which case go back to step two. The destination may be the same, but the second set invites error at every turn. Control flow is a set of directions for the machine, and it must also be followed by the reader.
This idea is often reduced to a rule against goto, which misses its point. It is about making the program's dynamic behaviour visible in its static text. Where it leads is to the structured constructs that are now standard in almost every language, and to later principles such as keeping functions short and each one focused on a single task.
Structure the program around its data and its parts
As the book moves from lines to whole programs, it argues that structure should follow the problem. A program should be divided into parts, such as subroutines or functions, each of which does one job well and can be understood on its own. The divisions should reflect natural divisions in the task, not arbitrary breaks in a long listing.
One of the book's quieter but important points is that the choice of data representation often decides how clear a program can be. If the data are arranged well, the code that handles them can be simple. If the data are arranged badly, no amount of care in the code will make it clear. The authors show cases where a program full of special cases became straightforward once the data were organised differently, for example by using a table rather than a chain of conditions.
An everyday comparison helps. Imagine a kitchen where spices, plates and pans are stored at random. Cooking requires constant searching and remembering. Reorganise the kitchen so that things used together are stored together, and the same meals become easy to cook. The cook did not become more skilled. The arrangement did the work. In programs, the data structure is the arrangement, and the code is the cooking.
Modularity has other benefits. A well-separated part can be tested on its own. It can be replaced without disturbing the rest. Its interface, the way other parts call it, can be made simple and stable even if its insides are complex. The authors encourage programmers to give each module a clear purpose and a clean interface, and to resist the urge to let modules reach into each other's internals.
This idea is often confused with simply splitting long code into shorter pieces. Breaking a long routine at arbitrary points does not create good structure; it scatters the confusion across several places. Good structure comes from asking what the natural parts of the problem are and building the program to match. This theme is developed at much greater depth in Niklaus Wirth's Algorithms + Data Structures = Programs, which sits beside this book on the shelf.
Programs fail at their edges
A fourth cluster of ideas concerns where programs go wrong. The authors observe that errors gather at boundaries. They appear at the first or last element of an array, at an empty input, at the largest or smallest value a variable can hold, at the moment input ends unexpectedly, or when data arrive in a form the programmer did not foresee. The middle of the normal case is usually fine. It is the edges that break.
From this follow several habits. Check that input is valid before using it, rather than assuming it is well formed. Decide what the program should do with bad input, and do it consistently. Test the boundary cases deliberately: no data, one item, the maximum number of items, values just inside and just outside allowed ranges. Make sure that loops do the right thing on their first and last passes, which is where off-by-one errors live.
An off-by-one error is a classic of the kind. A loop meant to process ten items processes nine or eleven, because the programmer confused whether a counter starts at zero or one, or whether the end condition uses less than or less than or equal. The bug is tiny, often invisible in normal testing, and can cause real damage. The authors' advice is to reason carefully about the boundaries and to test them explicitly.
Input and output deserve special care because they are where the program meets people. Users make typing errors, files are truncated, formats change. A program that crashes on the first unexpected input is fragile. A program that silently produces wrong results is worse. The authors favour programs that check, report problems clearly and handle the end of input gracefully.
This idea is often confused with defensive excess, where every line is surrounded by checks. The point is to check at the boundaries, where data enter the program or where assumptions change, so that the interior can rely on clean data. Where this leads is to modern ideas about validating input at system edges, about property-based and boundary testing, and about designing interfaces that make invalid states hard to represent.
Common blunders and how to catch them
The book gives specific attention to the ordinary mistakes that programmers make again and again. These include using a variable before it has been given a value, confusing similar names, assuming that floating-point arithmetic is exact, mixing up the order of arguments, and relying on behaviour that a particular compiler happens to provide but the language does not guarantee.
Floating-point numbers deserve a note. Computers represent most fractions only approximately, so two calculations that should give the same answer may differ in the last few digits. Code that tests such values for exact equality can fail mysteriously. The authors warn about this, and the warning is as true now as then. A program that adds one tenth to itself ten times and tests whether the result equals one may be surprised.
Their general advice for catching blunders is a mix of habits. Initialise variables explicitly. Let the language check what it can, such as types and declarations, rather than relying on implicit defaults. Read the code as a stranger would. Test with cases chosen to expose errors, not merely to confirm that the normal case works. And when a bug is found, ask whether others like it exist elsewhere in the program.
An analogy is a pilot's checklist. Experienced pilots still use checklists, not because they forget how to fly, but because certain errors are common, costly and easy to make under pressure. A programmer's awareness of common blunders works the same way. Knowing where errors usually hide makes them easier to find.
This idea is sometimes dismissed as trivial, since each blunder seems obvious once named. But obvious errors are made all the time, by skilled people, because they are easy to overlook in one's own work. The value lies in turning a vague sense that mistakes happen into a specific list of where to look.
Make it right before making it faster
The book's discussion of efficiency is one of its most often cited parts. The authors argue that programmers worry about speed too early and in the wrong places. They distort clear code to save small amounts of time in parts of the program that hardly ever run, while the real cost lies elsewhere. The result is programs that are both harder to read and no faster in practice.
The remedy has three parts. First, make the program correct and clear. Second, measure where it actually spends its time, using tools that count how often each part runs or how long it takes. Third, improve only the parts that matter, usually by choosing a better algorithm or data structure rather than by micro-adjustments to individual statements. The authors call the measuring step instrumentation, and they show how even simple counts can reveal that intuition about speed is often wrong.
Imagine a delivery business that wants faster service. The manager could ask drivers to shave seconds off each stop, which is tiring and saves little. Or the manager could look at the routes and find that drivers cross the city twice a day for no reason. Fixing the route saves hours. Programs are similar. The big gains come from the structure of the work, not from polishing each step.
The authors also point out that clear code is easier to optimise. When the structure is visible, you can see where a better algorithm would help. When the structure is buried under tricks, even finding the slow part is hard. Clarity and efficiency are not opposites. Clarity is the condition for efficient improvement.
This idea is often confused with a claim that efficiency does not matter. It does matter, sometimes greatly. The point is about order and method: correctness first, measurement second, targeted improvement third. It anticipates a remark by Donald Knuth, made in the same year, that premature optimisation is a root of much evil in programming. Where it leads is to modern profiling tools and the habit, now standard among careful engineers, of measuring before tuning.
Comments, documentation and the code itself
The book's view of documentation is distinctive. It holds that the best documentation is clear code. Comments are useful, but they cannot rescue code that is hard to understand. If a passage needs a long comment to explain what it does, the better course is usually to rewrite it so that it explains itself.
The authors identify several ways comments go wrong. They may simply repeat what the code already says, adding length without meaning. They may disagree with the code, either because they were wrong from the start or because the code changed and the comment did not. A wrong comment is worse than none, since readers tend to trust comments more than code. Comments may also be used to excuse a confusing design rather than to fix it.
Good comments, on this view, say what the code cannot: why a decision was made, what assumption it relies on, what the reader should know about the larger context. They should be kept short, accurate and close to the code they describe. Layout matters as well. Consistent indentation that shows structure, sensible grouping of related lines, and meaningful names all serve the same purpose as comments, and often serve it better.
An analogy helps. A good map needs few notes, because its symbols and layout already show the roads and rivers. A bad map needs paragraphs of explanation, and even then readers get lost. The cure for the bad map is to redraw it, not to add more notes. Code is the map; comments are the notes.
This idea is often taken to mean that comments are bad. That is too strong. The authors value comments that add information. Their target is comments that substitute for clarity. Where this leads is to the modern view, common in books such as Clean Code and A Philosophy of Software Design, that code should be self-explanatory where possible and comments should record intent and reasoning.
Learning by rewriting
Beyond its specific rules, the book teaches a method of learning: study bad code, understand why it is bad, and rewrite it. This is how writers have long learned style, by editing, and the authors apply it to programs. The reader is shown the before and the after, and the reasoning that leads from one to the other.
The method works because it trains perception. At first a reader may not see what is wrong with a piece of code; it runs, after all. After many examples, the reader begins to notice the signs: a condition that is harder to read than it should be, a loop with an odd shape, a variable whose purpose is unclear. This sensitivity is more valuable than any list of rules, because it applies to cases the rules never mention.
The method also teaches humility. The examples come from published books by competent people. If they could write unclear code, so can anyone. The reader learns to apply the same scrutiny to their own work, which is the hardest and most useful habit of all.
Readers can practise the method directly. Before reading the authors' rewrite of each example, try your own. Then compare. Sometimes yours will be different and equally good; sometimes it will reveal an issue you missed. Over time, this exercise builds the judgement the book is really about.
This idea is sometimes confused with code review as a gatekeeping step. Rewriting as practice is different. It is not about approving or rejecting code but about developing an eye. Where it leads is to refactoring as a discipline, described at length in Martin Fowler's book on this shelf, in which improving the design of existing code becomes a routine part of programming.
Do not reinvent what already exists
A recurring lesson in the book is that programmers too often write their own version of something that already exists. Textbook code computes square roots, sorts lists, converts numbers to text or searches tables by hand, when the language or its standard library already provides a tested routine for the purpose. The hand-written version is longer, slower to read and frequently wrong at its edges.
The reasons people reinvent are understandable. They may not know the library well. They may distrust code they did not write. They may enjoy the challenge. Or they may believe their version will be faster. The authors answer each in turn by example. Library routines have usually been written with more care and tested on more cases than any one programmer can manage in an afternoon. Using them makes the calling code shorter and its intent plain: a reader who sees a call to a familiar routine knows at once what is happening.
An everyday analogy fits. A builder who forges his own nails will spend days on something a hardware shop sells by the kilo, and his nails will probably be worse. Skill is better spent on the parts of the house that are unique to it. In programming, the unique parts are the logic of the problem at hand. Standard tasks belong to standard tools.
The lesson extends naturally from routines to tools and ideas. Kernighan's later work at Bell Labs, and the book he wrote with Plauger on software tools, both rest on the same principle: build small general pieces once, well, and reuse them. The UNIX Programming Environment, on this shelf, shows the principle at system scale, where small programs connected together solve problems none of them was written for.
This idea is sometimes stretched into a claim that one should never write anything that a library might provide. That goes too far. There are good reasons to write your own code: the library may not fit the problem, may be too heavy, or may hide behaviour you need to control. Modern programmers also know the risk of depending on large external packages whose quality they cannot see. The book's point is narrower and still sound: know what is available, prefer tested parts for standard jobs, and spend your own effort where it is needed.
Testing as part of writing
Although the book is about style, it treats testing as inseparable from writing. A clear program is easier to test, and the act of testing reveals where a program is unclear. The authors encourage programmers to think about how they will check their code while they are writing it, not after.
Their advice is practical. Test the simple cases first, then the boundaries, then cases chosen to break the program. Test each part on its own before testing the whole, so that when something fails you know where to look. Make programs report what they are doing in a way that can be checked, for example by printing intermediate values during development or by checking that results satisfy known properties. When a result is wrong, find the cause rather than adjusting the code until the symptom disappears.
One habit deserves special mention: checking a program's results against something independent. If a routine computes an average, check it on data where the average is known. If it sorts a list, check that the output is in order and contains the same items as the input. Such checks catch errors that a programmer reading his own code would miss, because they do not depend on the programmer's understanding being right.
Consider how an accountant checks a ledger. Adding the columns again in the same way will repeat any mistake. Adding them in a different order, or checking that debits equal credits, catches errors the first method missed. Good testing works the same way: it uses a second route to the truth.
This idea is easily confused with the large testing frameworks of later decades, which the book does not describe. Its point is more basic. Testing is a way of thinking about code, and code written with testing in mind tends to be clearer. Where this leads is to later practices such as unit testing and test-first development, described in Kent Beck's Extreme Programming Explained on this shelf, which make the habit systematic.
Layout, consistency and the look of code
The book treats the visual form of code as part of its meaning. Indentation that matches structure lets a reader see at a glance which statements belong to which loop or condition. Blank lines that separate logical groups show where one step ends and the next begins. Consistent naming, so that similar things have similar names, helps the reader form expectations that the code then fulfils.
In the era of the book's examples, much code was written in fixed columns on punched cards, and indentation was often neglected or impossible. The authors nonetheless show how layout, where available, transforms readability. A loop whose body is indented clearly looks like a loop. A loop whose body is flush with the surrounding code must be decoded.
Consistency matters beyond layout. If a program uses one convention for naming counters in one place and another elsewhere, readers will wonder whether the difference means something. If error handling is done one way in one routine and another way in the next, readers must learn both. Uniformity lets readers stop thinking about the form and attend to the substance.
A printed book is a useful comparison. Readers seldom notice good typography, but they notice bad typography immediately. Uneven spacing, inconsistent headings and random fonts make even good writing tiring to read. Code layout works the same way. When it is good, it disappears; when it is bad, it gets in the way.
This idea is sometimes trivialised into arguments about where braces go, which consume much energy in some teams. The book's concern is not with any particular convention but with having a consistent one that shows structure. Modern automatic formatters, which impose one layout on a whole codebase, solve the problem the book identified by removing the choice altogether, and free programmers to argue about things that matter.
Simplicity as a design choice
Running beneath many of the book's lessons is a preference for simplicity in the design of programs, not only in the writing of lines. The authors favour programs that do one thing well, with plain inputs and outputs, over programs that try to do many things and become tangled. They show cases where a program grew special cases until its logic was buried, and where a simpler design served the same purpose with less code and fewer errors.
Simplicity in this sense is not the same as small size or few features. A simple program can be large if its parts are clear and their relations plain. What makes a program complex is the number of things a reader must hold in mind at once to understand any part of it. Special cases, hidden dependencies and shared state all increase that number. Clear structure and clean interfaces reduce it.
The authors' preference reflects the culture of the Bell Labs group in which Kernighan worked, where small tools and plain designs were valued and where Unix itself grew from a deliberate rejection of the complexity of an earlier large system. The Elements of Programming Style does not describe that culture directly, but its sensibility is everywhere in the rewrites.
An analogy from machinery helps. A simple mechanism with few moving parts is easier to understand, repair and trust than an elaborate one, even if the elaborate one has more functions. Engineers learn to remove parts rather than add them. Programmers who learn the same instinct write code that lasts.
This idea leads directly to later thinking about complexity in software, notably John Ousterhout's argument in A Philosophy of Software Design that the main job of a designer is to manage complexity, and to the Unix philosophy described in The UNIX Programming Environment.
Rules as distilled judgement
The book's list of maxims is famous, and it is tempting to treat it as a set of laws. The authors' own approach suggests caution. Each rule is the summary of a case, a compressed reminder of a piece of reasoning. Applied without that reasoning, a rule can mislead. A rule against a certain construct may be right in most cases and wrong in a few, and only understanding tells you which case you are in.
This is a familiar pattern in any craft. A cookery rule such as salt pasta water generously is good advice, but a cook who understands why, because the pasta absorbs flavour as it cooks, will know when to adjust. A cook who follows the rule blindly will oversalt a dish where other salty ingredients are present. Programming rules are the same. They condense experience, and they work best when the experience is understood.
The authors model this by never stating a rule without its case. The rule comes after the reasoning, not before. Readers who absorb the reasoning can extend it to new situations and new languages. Readers who memorise only the list will be less able to judge exceptions, and will sometimes defend a rule where it does harm.
This view also explains why the book has aged well despite its old languages. The specific advice about Fortran constructs no longer applies to most readers. The reasoning that produced it applies everywhere. A reader today can take each maxim and ask what its equivalent would be in a modern language, and almost always find one.
Style when code is cheap to produce
A reader today meets the book in a world very different from 1974. Programs are no longer punched on cards. Editors highlight syntax, compilers catch many slips, and a growing share of code is produced by automated tools that can write a working routine in seconds. It is fair to ask whether a book about writing clear code by hand still matters.
The answer is that it matters more. When code was expensive to write, there was at least a natural limit on how much unclear code could accumulate. When code is cheap to produce, that limit disappears. A team can generate large amounts of working but muddled code quickly, and the cost of reading, checking and changing it falls on people later. The book's central claim, that programs are read far more than they are written, becomes sharper when writing costs almost nothing.
The book also offers a method for judging code one did not write. Its examples are, in a sense, code from outside sources, produced by competent authors and offered as correct. The authors read each one sceptically, ask what it is trying to do, check its boundaries, notice when it reinvents a library routine or hides its intent, and rewrite it. That is exactly the stance a careful programmer needs toward generated code: accept nothing because it runs, read it as a stranger would, and improve it until it says what it means.
The same faults recur. Generated code often contains needless temporary variables, roundabout conditions, duplicated logic, comments that restate the obvious, and missing checks at the edges. A reader trained by this book will spot these quickly. The maxims serve as a checklist for review, and the habit of rewriting serves as a way to turn acceptable code into good code.
There is a limit to this parallel. The book assumes that a human author will learn from the critique and write better next time. Tools learn differently, and the person reviewing generated code must keep their own judgement sharp rather than let it fade from disuse. Reading this book, and practising its exercises, is one way to keep that judgement in working order.
The tradition around it
The Elements of Programming Style came at the height of the structured programming movement. Dijkstra's letter against goto in 1968, and the book Structured Programming by Dahl, Dijkstra and Hoare in 1972, had argued that programs should be built from a small set of well-understood control structures. Kernighan and Plauger brought this argument down to earth, showing in concrete examples what it meant for everyday code.
The book also drew on the tradition of style manuals in English writing, as its title announces. That tradition holds that clarity can be taught, that rules distilled from good practice help writers improve, and that the best way to learn is to see bad writing made good. Applying this tradition to programs was a fresh step.
Within this shelf, the closest companion is The Psychology of Computer Programming by Gerald Weinberg, published three years earlier, which argued that programs are written for human readers and that their quality is a human matter. Kernighan and Plauger take that view and apply it line by line. The UNIX Programming Environment by Kernighan and Rob Pike shows the same values at the level of tools and systems: small programs, plain interfaces, clear composition.
Algorithms + Data Structures = Programs by Niklaus Wirth, published two years later, shares the conviction that data structure shapes program clarity, and develops it with mathematical care. Later books on the shelf carry the tradition forward. Code Complete by Steve McConnell gathers a vast amount of evidence and advice on construction, much of it in the same spirit. The Pragmatic Programmer by Andrew Hunt and David Thomas broadens the advice to a programmer's whole working life. Refactoring by Martin Fowler turns rewriting into a systematic practice with named steps. Clean Code by Robert C. Martin restates many of the same lessons for object-oriented code, sometimes more dogmatically. A Philosophy of Software Design by John Ousterhout argues that the central goal of design is to reduce complexity for the reader, which is the same goal pursued at a different scale.
The book's influence also shows in the later work of its authors. The C Programming Language and The Practice of Programming carry its style forward, and Kernighan's teaching and writing over several decades kept its lessons in circulation.
Questions and criticisms
The most obvious limitation is the languages. Fortran and PL/I are now rarely used outside specialised settings, and some of the book's specific advice concerns features those languages had or lacked. A modern reader has to translate. For most of the book this is easy, but a few discussions depend on details that now matter only historically.
Some critics have noted that the book, by working on small examples, says little about large-scale design. It teaches how to write clear routines and modest programs, but not how to organise a system of a million lines with many teams. This is fair, though it was never the book's aim. Large systems are made of small parts, and the clarity of those parts matters a great deal, but other books on this shelf are needed for the larger questions.
The choice of textbook examples has occasionally been seen as harsh. The authors criticise published work by named sources, though their tone is restrained and their aim is clearly instruction rather than ridicule. Some later writers have preferred to construct their own bad examples. Using real code, however, gives the book an authority that invented examples would lack: these errors were actually made by people who knew what they were doing.
Some advice has been refined. Views on efficiency, for instance, have shifted as hardware has grown faster and memory cheaper, so that some trade-offs the authors discussed have changed. The basic principle of measuring before tuning has only grown stronger, but particular judgements about what costs what may no longer hold. Similarly, modern languages offer constructs, such as exceptions and rich standard libraries, that change how some of the book's problems would be solved.
Another criticism applies more to the book's followers than to the book. Lists of rules, once famous, can harden into dogma. Some later style guides present rules without the reasoning, and some reviewers enforce them mechanically. The Elements of Programming Style itself resists this by always showing the case, but readers should be aware of the risk.
What has held up is the core: clarity first, say what you mean, structure that reads naturally, attention to boundaries, measure before tuning, and code that documents itself. These lessons are as relevant to code written today, including code produced by automated tools, as they were in 1974. Every large codebase contains examples of the faults the book describes.
A last point concerns evidence. The book argues by example and by the reader's own recognition, not by measured studies. Its claim that clear code has fewer errors and costs less to maintain is persuasive and widely accepted, and later research has broadly supported the value of readability and review. But the book itself does not prove it. A reader should take the maxims as distilled experience from skilled practitioners, which is valuable, while knowing that experience can be wrong in particular cases.
It is also worth noting what the book does not claim. It does not say that style alone makes good software. Requirements can be wrong, designs can be poor, and teams can fail for reasons no rewrite will fix. Style is a necessary condition for quality, not a sufficient one. The authors keep to their subject, and readers should not ask the book for more than it offers.
Why it is on this shelf
This shelf collects books that teach how systems work and how to reason about them well. The Elements of Programming Style earns its place by teaching a specific kind of reasoning: how to look at a piece of code, see what is wrong with it, and make it right. It does this with economy and precision, in a book short enough to read in a weekend.
Readers who come from other fields will find familiar ideas. A reader of Vedanta knows the value of saying exactly what is meant, without ornament, and of commentary that clarifies rather than obscures. A reader of science knows the discipline of checking boundary cases and measuring before claiming. A reader of economics knows that small costs repeated many times outweigh large one-time savings, which is the argument for clarity over cleverness. The book applies these habits of mind to a new material.
For anyone who writes code, reads code or reviews code produced by others or by machines, the book is a practical tool. Its list of maxims can be used as a checklist, and its method of rewriting can be practised on any codebase. The faults it describes are timeless because they come from the way people think, not from any particular language.
We keep it beside Weinberg's Psychology of Computer Programming, which explains why clarity matters to people, and Wirth's Algorithms + Data Structures = Programs, which explains how structure creates clarity at a deeper level. Together the three books cover the human, the textual and the structural sides of writing good programs.
How to read it
Start with the introductory chapter, which sets out the method and gives the first examples. Read it slowly. It shows the pattern every later chapter follows, and once you have seen it you will know how to read the rest.
Then work through the chapters on expressions and control structure. These contain many short examples and are the core of the book. For each example, cover the authors' discussion and rewrite, study the original code, and write down what you think is wrong and how you would fix it. Then read their version. This exercise is the most valuable thing you can do with the book. Do not rush it; one or two examples a sitting is a good pace.
On a first pass, do not worry about Fortran or PL/I syntax. Read it as you would read pseudocode, and ask the authors' explanations to fill in anything unclear. If a passage depends on a language feature that has no modern equivalent, note the general lesson and move on.
Read the chapters on program structure, input and output, and common blunders next. These are more varied and can be read at a faster pace, though the examples on boundary conditions reward careful attention. Keep a pencil handy and test the code mentally on edge cases: empty input, one item, the last item.
Read the chapter on efficiency and instrumentation with a modern profiler in mind. If you have a program of your own, try measuring where it spends its time before reading the chapter, and compare your guess with the result.
Finish with the chapter on documentation and the closing summary of rules. Copy the rules onto a single sheet, and next to each write a sentence in your own words about the case it came from. That sheet will serve you longer than the book itself.
After a month, return to a few examples you found hard and rewrite them again without looking. If your second rewrite is clearer than your first, the book has done its work.
From this shelf, read next The UNIX Programming Environment by Kernighan and Pike, which carries the same values into tools and systems. Then Algorithms + Data Structures = Programs by Wirth, for the structural side. When you are ready to apply the lessons to larger and older code, read Refactoring by Martin Fowler and Working Effectively with Legacy Code by Michael Feathers. For a modern statement of the design philosophy behind clarity, read A Philosophy of Software Design by John Ousterhout.
Questions to carry
- In the last piece of code I wrote, where did I choose cleverness over clarity, and what did it save?
- Could a stranger read this function from top to bottom and understand what it does?
- Does each condition say what I mean, or something that merely happens to be equivalent?
- Is there a library function that already does what I am writing by hand?
- How would this code behave with empty input, one item, or the largest allowed value?
- Where are the boundaries of this program, and do I check data as they cross them?
- Would a different arrangement of the data make this code simpler?
- Before tuning this code, have I measured where its time actually goes?
- Do my comments explain why, or only repeat what the code already says?
- Is there a comment here that no longer agrees with the code?
- If I needed a long comment to explain this passage, should I rewrite it instead?
- Which rule am I following without knowing the case it came from?
- Which of the book's faults do I see most often in code I review, including code generated by tools?
- Where in my own code would a better arrangement of data remove a chain of special cases?
- When I accept generated code, have I read it as carefully as I would read a colleague's?
Words to know
- Library routine: a tested, reusable piece of code supplied with a language or system for standard tasks such as sorting or mathematical functions.
- Formatter: a tool that automatically lays out code in a consistent style, settling questions of indentation and spacing.
- Style: in programming, the set of choices about how code is written that do not change what it does but change how easily it is read, checked and changed.
- Maxim: a short rule summarising a lesson; the book ends each discussion with one and collects them at the end.
- Fortran: an early high-level language for scientific computing, first released in the 1950s and used for many of the book's examples.
- PL/I: a large general-purpose language developed by IBM in the 1960s, also used for many examples.
- Structured programming: the approach of building programs from a small set of clear control structures such as sequence, selection and loops, avoiding unrestricted jumps.
- Goto: a statement that transfers control to a labelled line elsewhere in the program; heavy use produces code that is hard to follow.
- Spaghetti code: code whose control paths are so tangled by jumps that it is hard to trace.
- Control flow: the order in which a program's statements are executed, determined by conditions, loops and calls.
- Expression: a combination of values, variables and operators that produces a result.
- Module: a self-contained part of a program, such as a subroutine or function, with a defined purpose and interface.
- Interface: the way one part of a program is used by others, including what it takes in and what it returns.
- Boundary condition: a case at the edge of the allowed range of input or state, where errors tend to occur.
- Off-by-one error: a mistake in which a loop or index goes one step too far or stops one step short.
- Initialisation: giving a variable a defined starting value before it is used.
- Floating point: the approximate representation of real numbers in a computer, which can cause small rounding errors.
- Efficiency: how much time or memory a program uses; the book argues it should be pursued only after correctness and clarity, and only where measurement shows it matters.
- Instrumentation: adding counters or timers to a program to measure how often parts run and how long they take.
- Profiler: a tool that reports where a program spends its time, the modern form of the instrumentation the book recommends.
- Premature optimisation: tuning code for speed before knowing whether or where speed matters, usually at the cost of clarity.
- Self-documenting code: code whose names, structure and layout make its purpose clear without extensive comments.
- Refactoring: improving the structure of existing code without changing its behaviour; the book's rewrites are an early form of it.
A note on this edition
This is a study edition written for this shelf in our own words. It describes and discusses The Elements of Programming Style but does not reproduce its examples or its list of rules. The book itself is still in copyright. It is short, practical and best read with a pencil in hand, and it can be found through a library or a bookshop.