关于美国国家航空航天局的 10 条规则的评论

NASA has a list of 10 rules for software development from the perspective of writing embedded software for expensive spacecraft.

  • Rule 1: Restrict code to simple control flow constructs, ban goto, setjmp(), longjmp(), and recursion. Banning recursion can turn clear code into buggy spaghetti and the practical difference between a bounded loop and one that may never stop is often negligible.
  • Rule 2: All loops must have a fixed upper-bound that can be statically proven. Depth bounds on recursive procedures make them as safe as loops.
  • Rule 3: Do not use dynamic memory allocation after initialization. Simulating dynamic memory allocation is worse than using the real thing. It's better to use a memory allocator with known behavior and prove the memory in use is bounded. The ISO C standard makes it impossible to determine an upper bound on stack memory.
  • Rule 4: No function should be longer than 60 lines or what can fit on a single sheet of paper. In modern programming, the size of a sheet of paper may not be relevant as programmers read code on-screen. Nested procedures make it difficult to determine the size to count.
  • Rule 5: The assertion density should average to at least two assertions per function. Assertions are good documentation and debugging tools. They should be used to check the validity of arguments and data from external sources.
  • Rule 6: Data objects should be declared at the smallest possible scope. This is good advice for many languages, not just those with limited scope.
  • Rule 7: The return value of non-void functions and the validity of parameters should be checked. It's not practical to check every aspect of validity, but any check is better than none.
  • Rule 8: The use of the preprocessor should be limited. Recursive macro calls and variable argument lists in macros can be useful for debugging but are banned. Conditional macro processing is also controversial.
  • Rule 9: The use of pointers should be restricted. Function pointers are not permitted, which can make code harder to understand and maintain. There are legitimate uses for function pointers, such as simulating object-orientation and avoiding code duplication. Banning more than one level of dereferencing is also an assault on good programming, as it goes against the idea of abstract data types.
  • Rule 10: All code must be compiled with all compiler warnings enabled at the most pedantic setting and pass static source code analyses with zero warnings. This is good advice.

These rules are written for embedded systems but have implications for programming language processors and application software. The author questions some of the rules and provides examples and counterexamples to illustrate their pros and cons.

阅读 9
0 条评论