Key 1. Fundamental Theorem of Readability.
Code should be written to minimize the time it would take for someone else to understand it (Time-Till-Understanding metric).
Key 2. Packing Information into Names. Pack information into your names:
a. Choose Specific Words;
b. Finding More 'Colorful' Words, (Word Alternatives: send - deliver, dispatch, announce, distribute, route; find - search, extract, locate, recover; start - launch, create, begin, open; make - create, set up, build, generate, compose, add, new) ItТs better to be clear and precise than to be cute;
c. Avoid Generic Names Like tmp and retval;
d. Prefer Concrete Names over Abstract Names;
e. Attaching Extra Information to a Name;
f. Shorter Names Are Okay for Shorter Scope;
g. Use Name Formatting to Convey Meaning;
Key 3. Actively scrutinize your names by asking yourself, 'What other meanings could someone interpret from this name?'
Before you decide on a name, play devil's advocate and imagine how your name might be misunderstood. The best names are resistant to misinterpretation.
a. When it comes to defining an upper or lower limit for a value, max_ and min_ are good prefixes to use.
b. For inclusive ranges, first and last are good. For inclusive/exclusive ranges, begin and end are best because theyТre the most idiomatic.
c. When naming a boolean, use words like is and has to make it clear that itТs a boolean. Avoid negated terms (e.g., disable_ssl).
d. Beware of usersТ expectations about certain words. For example, users may expect get() or size() to be lightweight methods.
Key 4. Aestetics vs Design: Consistent style is more important than the 'right' style.
a. Use consistent layout, with patterns the reader can get used to.
b. Make similar code look similar.
c. Group related lines of code into blocks: Rearrange Line Breaks to Be Consistent and Compact; Use Column Alignment When Helpful; Break Code into 'Paragraphs';
Key 5. The purpose of commenting is to help the reader know as much as the writer did.
What not to comment:
- Facts that can be quickly derived from the code itself.
- 'Crutch comments' that make up for bad code (such as a bad function name)-fix the code instead.
Thoughts you should be recording include:
- Insights about why code is one way and not another ('director commentary').
- Flaws in your code, by using markers like: TODO: Stuff I haven’t gotten around to yet; FIXME: Known-broken code here; HACK: Admittedly inelegant solution to a problem; XXX: Danger! major problem here;
- The 'story' for how a constant got its value.
Put yourself in the reader’s shoes:
- Anticipate which parts of your code will make readers say 'Huh?' and comment those.
- Document any surprising behavior an average reader wouldn’t expect.
- Use 'big picture' comments at the file/class level to explain how all the pieces fit together.
- Summarize blocks of code with comments so that the reader doesn’t get lost in the details.
Key 6. Making Comments Precise and Compact: Comments should have a high information-to-space ratio
a. Avoid pronouns like 'it' and 'this' when they can refer to multiple things.
b. Describe a function’s behavior with as much precision as is practical.
c. Illustrate your comments with carefully chosen input/output examples.
d. State the high-level intent of your code, rather than the obvious details.
e. Use inline comments (e.g., Function(/* arg = */ ... ) ) to explain mysterious function
arguments.
f. Keep your comments brief by using words that pack a lot of meaning.
Key 7. Making Control Flow Easy to Read: Make all your conditionals, loops, and other changes to control flow as 'natural' as possible-written in a way that doesn't make the reader stop and reread your code.
a. In a comparison better to put the changing value on the left and the more stable value on the right.
b. You can also reorder the blocks of an if/else statement. Generally, try to handle the positive/easier/interesting case first.
c. Programming constructs, like ternary operator (: ?), do/while loop, and goto often result in unreadable code; usually best not to use them, as clearer alternatives almost always exist.
d. Nested code blocks require more concentration to follow along. Each new nesting requires more context to be 'pushed onto the stack' of the reader.
e. Returning early can remove nesting and clean up code in general. 'Guard statements' - simple cases at the top of the function are especially useful.
Key 8. Break down your giant expressions into more digestible pieces.
a. introduce 'explaining variables' that capture the value of some large subexpression. This approach has three benefits: breaks down a giant expression into pieces; documents the code by describing subexpression with a succinct name; helps the reader identify the main 'concepts' in the code.
b. manipulate your logic using De Morgan's laws—this technique can sometimes rewrite a boolean expression in a cleaner way (e.g., if (!(a && !b)) turns into if (!a || b)).
Key 9. How the variables in a program can quickly accumulate and become too much to keep track of. You can make your code easier to read by having fewer variables and making them as 'lightweight' as possible:
a. Eliminate variables that just get in the way.
b. Reduce the scope of each variable to be as small as possible.
c. Prefer write-once variables. Variables that are set only once (or const, final, or otherwise immutable) make code easier to understand.
Key 10. Extracting Unrelated Subproblems: separate the generic code from the project-specific code.
As it turns out, most code is generic. By building a large set of libraries and helper functions to solve the general problems, what’s left will be a small core of what makes your program unique.
Key 11. One Task at a Time: Code should be organized so that it's doing only one task at a time (defragmenting).
Key 12. Turning Thoughts into Code
a. Describe what code needs to do, in plain English, as you would to a colleague.
b. Pay attention to the key words and phrases used in this description.
c. Write your code to match this description.
Key 13. Writing Less Code: most readable code is no code at all [ Adventure, excitement-a Jedi craves not these things. ^ Yoda ]
Each new line of code needs to be tested, documented, and maintained. Further, the more code in your codebase, the 'heavier' it gets and the harder it is to develop in.
Avoid writing new lines of code by:
a. Eliminating nonessential features from your product and not overengineering.
b. Rethinking requirements to solve the easiest version of the problem that still gets the job done.
c. Staying familiar with standard libraries by periodically reading through their entire APIs.
Key 14. Testing and Readability: Test code should be readable so that other coders are comfortable changing or adding tests.
a. Make Tests Easy to Read and Maintain
b. Making Error Messages Readable
c. Pick the simplest set of inputs that completely exercise the code.
d. Prefer clean and simple test values that still get the job done.
e. Give your test functions a fully descriptive name so it’s clear what each is testing. Instead of Test1(), use a name like Test_
_____________________________________________________________________________
Books on Writing High-Quality Code
Code Complete: A Practical Handbook of Software Construction, 2nd edition, by Steve McConnell (Microsoft Press, 2004)
Rigorous and well-researched tome on all aspects of software construction, including code quality and more.
Refactoring: Improving the Design of Existing Code, by Martin Fowler et al. (Addison-Wesley Professional, 1999)
Great book that talks about the philosophy of incremental code improvements and contains a detailed catalog of many different refactorings, along with steps to take to make these changes with less chance of breaking things.
The Practice of Programming, by Brian Kernighan and Rob Pike (Addison-Wesley Professional, 1999)
Discusses various aspects of programming including debugging, testing, portability, and performance, with various coding examples.
The Pragmatic Programmer: From Journeyman to Master, by Andrew Hunt and David Thomas (Addison-Wesley Professional, 1999)
Collection of many good programming and engineering principles, organized into short discussions.
Clean Code: A Handbook of Agile Software Craftsmanship, by Robert C. Martin (Prentice Hall, 2008)
Book similar to ours (but Java-specific); explores other topics such as error handling and concurrency.
No comments:
Post a Comment