Progamming style guidelines

http://home.earthlink.net/~huston2/books/programming_books.html

 

The Practice of Programming
Brian Kernighan, Rob Pike

Style
  1. Use descriptive names for globals, short names for locals.
  2. Be consistent.
  3. Use active names for functions.
  4. Be accurate.
  5. Indent to show structure.
  6. Use the natural form for expressions.
  7. Parenthesize to resolve ambiguity.
  8. Break up complex expressions.
  9. Be clear.
  10. Be careful with side effects.
  11. Use a consistent indentation and brace style.
  12. Use idioms for consistency.
  13. Use else-ifs for multi-way decisions.
  14. Avoid function macros.
  15. Parenthesize the macro body and arguments.
  16. Give names to magic numbers.
  17. Define numbers as constants, not macros.
  18. Use character constants, not integers.
  19. Use the language to calculate the size of an object.
  20. Don't belabor the obvious.
  21. Comment functions and global data.
  22. Don't comment bad code, rewrite it.
  23. Don't contradict the code. Clarify, don't confuse.
Interfaces
  1. Hide implementation details.
  2. Choose a small orthogonal set of primitives.
  3. Don't reach behind the user's back.
  4. Do the same thing the same way everywhere.
  5. Free a resource in the same layer that allocated it.
  6. Detect errors at a low level, handle them at a high level.
  7. Use exceptions only for exceptional situations.
Debugging
  1. Look for familiar patterns.
  2. Examine the most recent change.
  3. Don't make the same mistake twice.
  4. Debug it now, not later.
  5. Get a stack trace.
  6. Read before typing.
  7. Explain your code to someone else.
  8. Make the bug reproducible.
  9. Divide and conquer.
  10. Study the numerology of failures.
  11. Display output to localize your search.
  12. Write self-checking code.
  13. Write a log file.
  14. Draw a picture.
  15. Use tools.
  16. Keep records.
Testing
  1. Test code at its boundaries.
  2. Test pre- and post-conditions.
  3. Use assertions.
  4. Program defensively.
  5. Check error returns.
  6. Test incrementally.
  7. Test simple parts first.
  8. Know what output to expect.
  9. Verify conservation properties.
  10. Compare independent implementations.
  11. Measure test coverage.
  12. Automate regression testing.
  13. Create self-contained tests.
Performance
  1. Automate timing measurements.
  2. Use a profiler.
  3. Concentrate on the hot spots.
  4. Draw a picture.
  5. Use a better algorithm or data structure.
  6. Enable compiler optimizations.
  7. Tune the code.
  8. Don't optimize what doesn't matter.
  9. Collect common subexpressions.
  10. Replace expensive operations by cheap ones.
  11. Unroll or eliminate loops.
  12. Cache frequently-used values.
  13. Write a special-purpose allocator.
  14. Buffer input and output.
  15. Handle special cases separately.
  16. Precompute results.
  17. Use approximate values.
  18. Rewrite in a lower-level language.
  19. Save space by using the smallest possible data type.
  20. Don't store what you can easily recompute.
Portability
  1. Stick to the standard.
  2. Program in the mainstream.
  3. Beware of language trouble spots.
  4. Try several compilers.
  5. Use standard libraries.
  6. Use only features available everywhere.
  7. Avoid conditional compilation.
  8. Localize system dependencies in separate files.
  9. Hide system dependencies behind interfaces.
  10. Use text for data exchange.
  11. Use a fixed byte order for data exchange.
  12. Change the name if you change the specification.
  13. Maintain compatibility with existing programs and data.
  14. Don't assume ASCII.
  15. Don't assume English.
 
 

The Elements of Programming Style
Brian Kernighan, P. J. Plauger

Introduction
  1. Write clearly - don't be too clever.
Expression
  1. Say what you mean, simply and directly.
  2. Use library functions.
  3. Avoid temporary variables.
  4. Write clearly - don't sacrifice clarity for "efficiency."
  5. Let the machine do the dirty work.
  6. Replace repetitive expressions by calls to a common function.
  7. Parenthesize to avoid ambiguity.
  8. Choose variable names that won't be confused.
  9. Avoid the Fortran arithmetic IF.
  10. Avoid unnecessary branches.
  11. Use the good features of a language; avoid the bad ones.
  12. Don't use conditional branches as a substitute for a logical expression.
  13. Use the "telephone test" for readability.
Control Structure
  1. Use DO-END and indenting to delimit groups of statements.
  2. Use IF-ELSE to emphasize that only one of two actions is to be performed.
  3. Use DO and DO-WHILE to emphasize the presence of loops.
  4. Make your programs read from top to bottom.
  5. Use IF, ELSE IF, ELSE IF, ELSE to implement multi-way branches.
  6. Use the fundamental control flow constructs.
  7. Write first in an easy-to-understand pseudo-language; then translate into whatever language you have to use.
  8. Avoid THEN-IF and null ELSE.
  9. Avoid ELSE GOTO and ELSE RETURN.
  10. Follow each decision as closely as possible with its associated action.
  11. Use data arrays to avoid repetitive control sequences.
  12. Choose a data representation that makes the program simple.
  13. Don't stop with your first draft.
Program Structure
  1. Modularize. Use subroutines.
  2. Make the coupling between modules visible.
  3. Each module should do one thing well.
  4. Make sure every module hides something.
  5. Let the data structure the program.
  6. Don't patch bad code ?rewrite it.
  7. Write and test a big program in small pieces.
  8. Use recursive procedures for recursively-defined data structures.
Input and Output
  1. Test input for validity and plausibility.
  2. Make sure input cannot violate the limits of the program.
  3. Terminate input by end-of-file or marker, not by count.
  4. Identify bad input; recover if possible.
  5. Treat end of file conditions in a uniform manner.
  6. Make input easy to prepare and output self-explanatory.
  7. Use uniform input formats.
  8. Make input easy to proofread.
  9. Use free-form input when possible.
  10. Use self-identifying input. Allow defaults. Echo both on output.
  11. Localize input and output in subroutines.
Common Blunders
  1. Make sure all variables are initialized before use.
  2. Don't stop at one bug.
  3. Use debugging compilers.
  4. Initialize constants with DATA statements or INITIAL attributes; initialize variables with executable code.
  5. Watch out for off-by-one errors.
  6. Take care to branch the right way on equality.
  7. Avoid multiple exits from loops.
  8. Make sure your code "does nothing" gracefully.
  9. Test programs at their boundary values.
  10. Program defensively.
  11. 10.0 times 0.1 is hardly ever 1.0.
  12. Don't compare floating point numbers just for equality.
Efficiency and Instrumentation
  1. Make it right before you make it faster.
  2. Keep it right when you make it faster.
  3. Make it clear before you make it faster.
  4. Don't sacrifice clarity for small gains in "efficiency."
  5. Let your compiler do the simple optimizations.
  6. Don't strain to re-use code; reorganize instead.
  7. Make sure special cases are truly special.
  8. Keep it simple to make it faster.
  9. Don't diddle code to make it faster ?find a better algorithm.
  10. Instrument your programs. Measure before making "efficiency" changes.
Documentation
  1. Make sure comments and code agree.
  2. Don't just echo the code with comments ?make every comment count.
  3. Don't comment bad code ?rewrite it.
  4. Use variable names that mean something.
  5. Use statement labels that mean something.
  6. Format a program to help the reader understand it.
  7. Indent to show the logical structure of a program.
  8. Document your data layouts.
  9. Don't over-comment.
 

Practical Java
Peter Haggar

General Techniques
  1. Understand that parameters are passed by value, not by reference.
  2. Use final for constant data and constant object references.
  3. Understand that all non-static methods can be overridden by default.
  4. Choose carefully between arrays and Vectors.
  5. Prefer polymorphism to instanceof.
  6. Use instanceof only when you must.
  7. Set object references to null when they are no longer needed.
Objects and Equality
  1. Differentiate between reference and primitive types.
  2. Differentiate between == and equals.
  3. Do not rely on the default implementation of equals.
  4. Implement the equals method judiciously.
  5. Prefer getClass in equals method implementations.
  6. Call super.equals of base classes.
  7. Consider carefully instance of in equals method implementations.
  8. Follow these rules when implementing an equals method.
Exception handling
  1. Know the mechanics of exception control flow.
  2. Never ignore an exception.
  3. Never hide an exception.
  4. Consider the drawback to the throws clause.
  5. Be specific and comprehensive with the throws clause.
  6. Use finally to avoid resource leaks.
  7. Do not return from a try block.
  8. Place try/catch blocks outside of loops.
  9. Do not use exceptions for control flow.
  10. Do not use exceptions for every error condition.
  11. Throw exceptions from constructors.
  12. Return objects to a valid state before throwing an exception.
Performance
  1. Focus initially on design, data structures, and algorithms.
  2. Do not rely on compile-time code optimization.
  3. Understand runtime code optimization.
  4. Use StringBuffer, rather than String, for concatenation.
  5. Minimize the cost of object creation.
  6. Guard against unused objects.
  7. Minimize synchronization.
  8. Use stack variables whenever possible.
  9. Use static, final, and private methods to allow in lining.
  10. Initialize instance variables only once.
  11. Use primitive types for faster and smaller code.
  12. Do not use an Enumeration or an Iterator to traverse a Vector.
  13. Use System array copy for copying arrays.
  14. Prefer an array to a Vector or ArrayList.
  15. Reuse objects whenever possible.
  16. Use lazy evaluation.
  17. Optimize source code by hand.
  18. Compile to native code.
Multithreading
  1. Understand that for instance methods, synchronized locks objects, not methods or code.
  2. Distinguish between synchronized statics and synchronized instance methods.
  3. Use private data with an accessor method instead of public or protected data.
  4. Avoid unnecessary synchronization.
  5. Use synchronized or volatile when accessing shared variables.
  6. Lock all objects involved in a single operation.
  7. Acquire multiple locks in a fixed, global order to avoid deadlock.
  8. Prefer notifyAll to notify.
  9. Use spin locks for wait and notifyAll.
  10. Use wait and notifyAll instead of polling loops.
  11. Do not reassign the object reference of a locked object.
  12. Do not invoke the stop or suspend methods.
  13. Terminate threads through thread cooperation.
Classes and Interfaces
  1. Use interfaces to support multiple inheritance.
  2. Avoid method clashes in interfaces.
  3. Use abstract classes when it makes sense to provide a partial implementation.
  4. Differentiate between an interface, abstract class, and concrete class.
  5. Define and implement immutable classes judiciously.
  6. Use clone for immutable objects when passing or receiving object references to mutable objects.
  7. Use inheritance or delegation to define immutable classes.
  8. Call super.clone when implementing a clone method.
  9. Do not rely on finalize methods for non-memory resource cleanup.
  10. Use care when calling non-final methods from constructors.
 

Effective Java
Joshua Bloch

Creating and Destroying Objects
  1. Consider providing static factory methods instead of constructors
  2. Enforce the singleton property with a private constructor
  3. Enforce noninstantiability with a private constructor
  4. Avoid creating duplicate objects
  5. Eliminate obsolete object references
  6. Avoid finalizers
Methods Common to All Objects
  1. Obey the general contract when overriding equals
  2. Always override hashCode when you override equals
  3. Always override toString
  4. Override clone judiciously
  5. Consider implementing Comparable
Classes and Interfaces
  1. Minimize the accessibility of classes and members
  2. Favor immutability
  3. Favor composition over inheritance
  4. Design and document for inheritance or else prohibit it
  5. Prefer interfaces to abstract classes
  6. Use interfaces only to define types
  7. Favor static member classes over nonstatic
Substitutes for C Constructs
  1. Replace structures with classes
  2. Replace unions with class hierarchies
  3. Replace enum constructs with classes
  4. Replace function pointers with classes and interfaces
Methods
  1. Check parameters for validity
  2. Make defensive copies when needed
  3. Design method signatures carefully
  4. Use overloading judiciously
  5. Return zero-length arrays, not nulls
  6. Write doc comments for all exposed API elements
General Programming
  1. Minimize the scope of local variables
  2. Know and use the libraries
  3. Avoid float and double if exact answers are required
  4. Avoid strings where other types are more appropriate
  5. Beware the performance of string concatenation
  6. Refer to objects by their interfaces
  7. Prefer interfaces to reflection
  8. Use native methods judiciously
  9. Optimize judiciously
  10. Adhere to generally accepted naming conventions
Exceptions
  1. Use exceptions only for exceptional conditions
  2. Use checked exceptions for recoverable conditions and run-time exceptions for programming errors
  3. Avoid unnecessary use of checked exceptions
  4. Favor the use of standard exceptions
  5. Throw exceptions appropriate to the abstraction
  6. Document all exceptions thrown by each method
  7. Include failure-capture information in detail messages
  8. Strive for failure atomicity
  9. Don't ignore exceptions
Threads
  1. Synchronize access to shared mutable data
  2. Avoid excessive synchronization
  3. Never invoke wait outside a loop
  4. Don't depend on the thread scheduler
  5. Document thread safety
  6. Avoid thread groups
Serialization
  1. Implement Serializable judiciously
  2. Consider using a custom serialized form
  3. Write readObject methods defensively
  4. Provide a readResolve method when necessary
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值