Code Complete阅读笔记(二)

   2015-03-06   328   Unusual Data Types
    ——You can carry this technique to extremes,putting all the variables in your program into one big,juicy variable and then passingit everywhere.Careful programmers avoid bundling data any more than is logically necessary.
    ——Even if your language doesn't require you to use pointers,a good understanding of pointers will help your understanding of how your programming language works.
    ——Working with pointers successfully requires a two-pronged strategy.First,avoid installing pointer errors in the first place.Second,detect pointer errors as soon after they are coded as possible.
    ——By minimizing the number of places in which pointers are accessed,you minimize the possibility of making careless mistakes that spread throughout your program and take forever to find.

 

    2015-03-07   333   Unusual Data Types

    ——If your code contains a complicated expression,assign it to a well-named variable to clarify the intent of the operation.
    ——One way to give your program a margin of error is to preallocate a memory parachute.
    ——You can minimize programming overhead and reduce chance of errors by creating cover routins for common pointer operations.In C++,you could use these two routines:SAFE_NEW and SAFE_DELETE.
    问题:如何实现上文中提到的SAFE_NEW和SAFE_DELETE方法?

    ——If you can think of an alternative to using a pointer that works reasonably,save yourself a few headaches and use it instead.

 

    2015-03-10   340   Unusual Data Types
    问题:什么是智能指针?
    ——A program that requires many type casts probably has some architectural gaps that need to be revisited.
    ——Modularity,information hiding,and the associated use of well-designed classes might not be revealed truths,but they go a long way toward making large programs understandable and maintainable.
    ——The essence of creating programs that are larger than a few hundred lines of code is managing complexity.The only way you can intellectually manage a large program is to break it into pieces so that you only have to think about one part a time.
    问题:什么情况下使用全局数据是合适的?语言纯化论者的观点有道理吗?
    ——If you start by making a variable global,you'll never make it local,whereas if you start by making it local,you might never need to make it global.
    问题:使用访问程序(Access Routines)有什么好处?
    ——It's a small gain in readability,but consistent attention to such details makes the difference between beautifully crafted software and code that's just hacked together.

 

 

   2015-03-11   347   Unusual Data Types
    ——If you throw all your global data into a big pile and write access routines for it,you eliminate the problems of global data but you miss out some of the advantages of information hiding and abstract data types.
    ——Build access routines at the level of the problem domain rather than at the level of the implementation details.
    问题:访问函数如何体现出信息隐藏的优势?
    ——Don't pretend you're not using global data by putting all your data into a monster object and passing it everywhere.
    问题:本章包含三种特殊数据类型,结构体,全局数据和指针,为什么说他们是特殊的?

 

    2015-03-12   354   Organizing Straight-Line Code
    ——When statements have dependencies that require your to put them in a certain order,take steps to make the dependencies clear.
    ——By rewriting the code so that data is passed between the routines,you set up a clue that the execution order is important.
    ——Try first to write code without order dependencies.Try second to write code that makes dependencies obvious.If you're still concerned that an order dependency isn't explicit enough,document it.
    问题:什么是无序代码的“就近原则”?
    ——As a general principle,make the program read from top to bottom rather than jumping around.
    ——Once you've grouped related statements,you might find that they're strongly related and have no meaningful relationship to the statements that precede or follow them.In such a case,you might want to refactor the strongly related statements into their own routine.
    问题:有哪些方法体现线性代码的依赖关系?
    ——Dependencies should be made obvious through the use of good routine names,parameter lists,comments,and-if the code is critical enough-housekeeping variables.

 

    2015-03-13   364   Using Conditionals
    ——Put the case you normally expect to process first.This is in line with the general principle of putting code that results from a decision as close as possible to the decision.
    问题:面对多种错误结果造成的深层嵌套If语句,有哪些方法可以优化其可读性?
    ——Coding null elses just to show that that case has been considered might be overkill,but at the very least,take the else case into account.
    ——By putting the most common cases first,you minimize the amount of exception-case handling code someone has to read to find the usual cases.You improve efficiency because you minimize the number of tests the code does to find the most common cases.
    ——Code a final else clause with an error message or assertion to catch cases you didn't plan for.
    ——If you have a long case statement-for example,a case statement that handles dozens of events in an event-driven program-order is significant.
    问题:使用case语句时有哪些注意事项?

 

    2015-03-16   375   Controlling Loops
    ——Using loops is one of the most complex aspects of programming;knowing how and when to use each kind of loop is a decisive factor in constructing high-quality software.
    ——In common practice,the loop-with-exit loop isn't widely used yet.The jury is still locked in a smoky room arguing about whether is's a good practice for production code.
    ——The for loop is for simple uses.Most complicated looping tasks are better handled by a while loop.
    ——Treat the inside of the loop as if it were a routine-kiip as much of the control as possible ouside the loop.
    问题:关于循环入口,有哪些注意事项?
    ——Keep loop-initialization statements with the loop they're related to.If you don't,you're more likely to cause errors when you generalize the loop into a bigger loop and forget to modify the initialization code.
    问题:为什么在合适的情况下,更偏好for循环?
    ——Reserve the for loop header for loop-control statements-statements that initialize the loop,terminate it,or move it toward termination.

 

    2015-03-17   384   Controlling the Loop
    ——As a general rule,the variables you initialize before the loop are the variables you'll manipulate in the housekeeping part of the loop.
    ——Loops should be like routines in that each one should do only one thing and do it well.
    ——If it seems inefficient to use two loops where one would suffice,write the code as two loops,comment that they could be combined for efficiency,and then wait until benchmarks show that the section of the program poses a performance problem before changing the two loops into one.
    问题:在不同情况下,如何让循环结束条件更明显?
    ——When you set up a for loop,the loop counter is off limits.Use a while loop to provide more control over the loop's exit conditions.
    ——A proliferation of breaks raises the possibility that the loop could be more clearly expressed as a series of loops rather than as one loop with many exits.
    ——Java supports use of labeled breaks to prevent the kind of problem experienced with the New York City telephone outage.
    ——It really is a simple proposition:if you can't defend a break or a continue,don't use it.
    ——Efficient programmers do the work of mental simulations and hand calculations because they know that such measures help them find errors.
    问题:为什么要在大脑中真正想明白循环如何工作,而不是通过修改控制条件等来尝试?
    ——In general,if the body of a loop has more than a couple of lines,if it might grow,or if it's in a group of nested loops,avoid i,j,and k.

 

    2015-03-18   390   Controlling Loops
    ——When you begin to appreciate the principle of writing simple code,however,you'll rarely write loops longer than 15 or 20 lines.
    问题:如何把循环嵌套深度控制在3层以下?
    ——If the loop is well designed,the code on the inside of a loop can often be moved into one or more routines that are called from within the loop.
    ——The idea is to start with something concrete,worry about only one thing at a time,and build up the loop from simple components.Take small,understandable steps as you make the loop more general and complex.
    ——The language you use to solve a problem substantially affects your solution.
    问题:为什么要由内而外地构造复杂循环,如何操作?
    ——Loop indexes are subjected to a great deal of abuse.Name them clearly,and use them for only one purpose.
    ——Loops are complicated.Keeping them simple helps readers of your code.

 

    2015-03-19   394   Unusual Control Structures
    问题:你能想到哪些特殊控制结构?
    ——Several control constructs exist in a hazy twilight zone somewhere between being leading-edge and being discredited and disproved-often in both places at the same time!
    ——Indenting the main body of the routine inside four if statements is aesthetically ugly,especially if there's much code inside the innermost if statement.
    问题:遇到上文的情况,如何重构代码?
    ——Recursion is usually called into play when a small part of the problem is easy to solve and a large part is easy to decompose into smaller pieces.
    ——For a small group of problems,recursion can produce simple,elegant solutions.For a slightly larger group of problems,it can produce simple,elegant,hard-to-understand solutions.For most problems,it produces massively complicated solutions.

 

    2015-03-20   400   Unusual Control Structures
    问题:如何用递归实现快速排序?
    ——If you have cyclic recursion,you can usualy redesign the routines so that the recursion is restricted to a single routine.If you can't and you still think that recursion is the best approach,use safety counters as a recursive insurance policy.
    问题:使用递归时如何防止栈溢出?
    ——Use new to create objects on the heap rather than letting the compiler create auto objects on the stack.
    问题:用递归计算阶乘或斐波那契数为什么是不合适的?
    ——Most important,you should consider alternatives to recursion before using it.You can do anything with stacks and iteration that you can do with recursion.
    ——Code containing gotos is hard to format.Indentation should be used to show logical structure,and gotos have an effect on logical structure.Using indentation to show the logical structure of a goto and its target,however,is difficult or impossible.
    问题:什么情况下,goto表面上增加了效率,实际上却降低了效率?
    ——A well-placed goto can eliminate the need for duplicate code.Duplicate code leads to problems if the two sets of code are modified differently.Duplicate code increases the size of source and executable files.
    ——Achieving goto-less code is not the aim but the outcome,and puting the focus on avoiding gotos isn't helpful.

 

    2015-03-23   408   Unusaul Control Structures
    ——What's not usually addressed,however,is the situation in which a programmer fully aware of the goto-less alternatives chooses to use a goto to enhance readability and maintainability.
    ——Writing highly interactive code calls for paying a lot of attention to error processing and cleaning up resource when errors occur.
    ——A programmer might balance the evil of the goto against the headache of duplicate-code maintenance and decide that the goto the the lesser evil.
    问题:在处理多重的错误状态时,goto和深层嵌套的if语句哪个更好?
    ——To rewrite using the try-finally approach,enclose the code that would otherwise need to check for errors inside a try block,and place the cleanup code inside a finally block.
    ——The limitation of the try-finally approach is that it must be implemented consistently throughout a code base.
    问题:goto,if嵌套,状态值和异常四种方式,应该灵活选择还是一致地使用?
    ——If you have your rain boots on,it's not worth walking around the block to avoid a mud puddle.But keep your mind open to a goto-less approaches suggested by other programmers.They might see something you don't.
    ——If you're a manager,adopt the perspective that a battle over a single goto isn't worth the loss of the war.If the programmer is aware of the alternatives and is willing to argue,the goto is probably OK.

 

    2015-03-24   416   Table-Driven Methods
    ——The field of software development has advances largely through restricting what programmers can do with their code.
    ——Fowler suggests using multiple return statements from a routine to reduce nesting in a set of if statements.(Refactoring,Replace Nested Conditional with Guard Clauses)
    ——"A Linguistic Contribution of GOTO-less Programming",this classic paper humorously argues for replacing the "go to" statement with the "come from" statement.
    问题:什么是表驱动法?
    ——A table-driven method is a scheme that allows you to look up information in a table rather than using logic statements(if and case)to figure it out.Virtually anything you can select with logic statements,you can select with tables instead.
    问题:为什么有些情况下适合用表驱动法替代分支语句?
    ——An object-oriented design isn't necessarily better than any other kind of design just because it's object-oriented.
    ——When you use table-driven methods,you have to address two issues.First you have to address the question of how to look up entries in the table.The second issue you have to address if you're using a table-driven method is what yo should store in the table.
    ——If you need to classify data by Social Security Number,for example,you can't use the Social Security Number to key into the table directly unless you can afford to store 999-99-9999 entries in your table.
    问题:如何解决上面的问题?
    ——Direct Access:you don't have to jump through any complicated hoops to find the information you want in the table.You can pick out the entry you want directly.
    ——One advantage of a table-driven approach is that you can put the table's data in a file and read it at run time.That allows you to change something like an insurance rates table without changing the program itself.

 

    2015-03-25   426   Table-Driven Methods
    问题:“浮标”案例如何体现表驱动法的优势?
    ——Once message definitions are read into the program,instead of having all the information embedded in a program's logic,you have it embedded in data.Data tends to be more flexible than logic.Data is easy to change when a message format changes.
    ——Another approach would be to create an abstract class AbstractField and then create subclasses for each field type.You won't need a case statement;you can call the member routine of the appropriate type of object.
    ——Once the table of routine is set up,you can handle a field in the message simply by accessing the table of objects and calling one of the member routines in the table.
    问题:参考上面,“浮标”案例中,直接的面向对象为什么不合适?如何将面向对象和表驱动法结合起来?
    ——You can use this approach in any object-oriented language.It's less error-prone,more maintainable,and more efficient than lengthy if statements,case statements,or copious subclasses.
    问题:什么情况下表中数据难以用键直接查询?有哪几种方法解决?各有什么优劣?
    ——If your environment provides ready-made key transformations,use them.For example,Java provides HashMap,which can be used to associate key/value pairs.
    ——When you use indexes,you use the primary data to look up a key in an index table and then you use the value from the index table to look up the main data you're interested in.
    问题:索引访问方案有哪些优势?

 

    2015-03-26   430   Table-Driven Methods
    ——Put the index-access code in its own routine and call the routine when you need to get a table key from a part number.
    ——The access scheme will be easier to change if you don't spread index accesses throughout your program.
    ——The stair-step approach categorizes each entry by determining the level at which it hits a "staircase".The "step" it hits determines its category.
    问题:什么情况下阶梯方法优于索引方法?
    ——The advantage of this approach over other table-driven methods is that it works well with irregular data.
    ——Consider using a binary search rather then a sequential search.
    问题:什么情况下可以用索引方法代替阶梯方法?
    ——The searching required in the stair-step method can add up,and if execution speed is a concern,you might be willing to trade the space an extra index structure takes up for the time advantage you get with a more direct access method.
    ——The point of design is choosing one of the several good options for your case.Don't worry too much about choosing the best one-it's better to strive for a good solution and avoid disaster rather than trying to find the best solution.
    问题:表驱动法是如何替代复杂逻辑或复杂继承结构的?
    ——One key consideration in using a table is deciding how to access the table.You can access tables by using direct access,indexed access,or stair-step access.

 

    2015-03-27   442   General Control Issues
    ——Except for the simplest control structure,the one that calls for the execution of statements in sequence,all control structures depend on the evaluation of boolean expressions.
    ——If a test is repeated often or distracts from the main flow of the program,move the code for the test into a function and test the value of the function.
    ——Not a few people don't have not any trouble understanding a nonshort string of nonpositives-that is,most people have trouble understanding a lot of negatives.
    问题:什么是狄摩根定理?如何使用?
    ——If you're smart,you won't depend on your own or your reader's in-depth memorization of evaluation precedence-expecially when you have to switch among two or more languages.
    ——Parentheses are cheap,and they aid readability.Fully parenthesizing logical expressions as a matter of havit is good practice.
    ——Better yet,since a reader of your code might not be as sharp as you are,use nested tests to clarify your intentions instead of depending on evaluation order and short-circuit evaluation.
    ——Organize numeric tests so that they follow the points on a number line.The idea is to order the elements left to right,from smallest to largest.
    ——Some C conventions aren't based on maximizing readability or maintainability,and this is an example of one.Fortunately,this whole issue if fading into the sunset as more code is written using C++ and STL strings.

 

   2015-03-30   454   General Control Issues
   ——Turning on full compiler warnings is usually a better option than creating nonstandard macros.
   ——Putting a single statement after an if test is sometimes appealing aesthetically,but under maintenance such statements tend to become more complicated blocks,and single statements are error-prone when that happens.
   ——Most of the code that results in loops with empty bodies relies on side effects in the loop-control code.In most cases,the code is more readable when the side effects are made explicit.
   问题:为什么避免深层嵌套(三或四层以上)仍是编程的关键问题之一?
   ——You can't reduce the nesting level for free;you have to put up with a more complicated test in return for the reduce level of nesting.
   ——If deep nesting occurs inside a loop,you can often improve the situation by putting the inside of the loop into its own routine.This is especially effective if the nesting is a result of both conditionals and iterations.
   ——In a system of any size,the switch statement would be converted to use a factory method that could be reused anywhere an object of Transaction type needed to be created.
   问题:上面这句话针对的具体案例是什么?
   ——More generally,complicated code is a sign that you don't understand your program well enough to make it simple.Deep nesting is a warning sign that indicates a need to break out a routine or redesign the part of the code that's complicated.
   问题:本书一共介绍了哪些减少深层嵌套的方法?

 

    2015-04-01   461   General Control Issues
    ——The core of structured programming is the simple idea that a program should use only one-in,one-out control constructs.
    ——A one-in,one-out control construct is a block of code that has only one place it can start and only on place it can end.It has no other entries or exits.
    ——The core thesis of structured programming is that any control flow whatsoever can be created from these three constructs of sequence,selection,and iteration.
    ——Programming seems to have advanced largely by restricting what we are allowed to do with our programming languages.
    ——My belief is that use of any control structure other than the three standard structured programming constructs-that is,the use of break,continue,return,throw-catch,and so on-should be viewed with a critical eye.
    ——The competent programmer is fully aware of the strictly limited size of his own skull;therefore,he approaches the programming task in full humility.
    ——You can better deal with complexity in one of two ways.First,you can improve your own mental juggling abiities by doing mental exercises.Second,you can decrease the complexity of your programs and the amount of concentration required to understand them.
    问题:有哪些方法衡量程序复杂度?
    ——The maximum of 10 decision points isn't an absolute limit.Use the number of decision points as a warning flag that indicates a routine might need to be redesigned.Don't use it as an inflexible rule.

 

    2015-04-03   467   The Software-Quality Landscape
    问题:什么是软件的外在质量特性?软件有哪些外在质量特性?
    ——External characteristics of quality are the only kind of software characteristics that users care about.
    问题:什么是软件的内在质量特性?软件有哪些内在质量特性?
    ——Understandability has to do with the coherence of the system at a more general level than readability does.
    ——The point is that some quality characteristics are emphasized to make life easier for the user and some are emphasized to make life easier for the programmer.Try to know which is which and when and how these characteristics interact.
    ——The attempt to maximize certain characteristics inevitably conflicts with the attempt to maximize others.Finding an optimal solution from a set of competing objectives is one activity that makes software development a true engineering discipline.
    ——It's useful to think about your specific quality goals and whether each pair of your goals is mutually beneficial or antagonistic.
    ——Although it might seem that the best way to develop a high-quality product would be to focus on the product itself,in software quality assurance you also need to focus on the software-development process.
    问题:为什么要设定明确的软件质量目标?如何设定此类目标?
    ——One common problem in assuring quality is that quality is perceived as a secondary goal.Indeed,in some organizations,quick and dirty programming is the rule rather than the exception.
    ——Developers on many projects rely on testing as the primary method of both quality assessment and quality improvement.This is too heavy a burden for testing to bear by itself.
    ——Many software developers review their work before turning it over for formal review.Informal reviews include desk-checking the design or the code or walking through the code with a few peers.

 

    2015-04-07   473   The Software-Quality Landscape
    ——One part of managing a software-engineering process is catching problems at the "lowest-value" stage-that is,at the time at which the least investment has been made and at which problems cost the least to correct.
    问题:什么是质量门限?可以包含哪些活动?
    ——The natural effect of change is to destabilize and degrade quality,so handling changes effectively is a key to achieving high quality levels.
    ——Prototyping can lead to better designs,better matches with user needs,and improved maintainability.
    ——Programmers have high achievement motivation:They will work to the objectives specified,but they must be told what the objectives are.
    ——The strong implication is that if project developers are striving for a higher defect-detection rate,they need to use a combination of techniques.
    ——A combination of unit testing,functional testing,and system testing often results in a cumulative defect detection of less than 60 percent,which is usually inadequate for production software.
    问题:极限编程的缺陷移除率为什么会明显好于平均水平?
    ——The determination of which specific defect-removal practices to use to achieve a desired quality level is one part of effective project planning.
    ——Some techniques,such as inspections,detect the symptoms and causes of defects in one step;others,such as testing,find symptoms but require additional work to diagnose and fix the root cuase.
    ——Just as it's a good idea to work out the defects in the blueprints for a house before pouring the foundation in concrete,it's a good idea to catch requirements and architecture errors before they affect later activities.

 

    2015-04-08   478   The Software_Quality Landscape
    ——The General Principle of Software Quality is that improvint quality reduces development costs.
    ——The single biggest activity on most projects is debugging and correcting code that doesn't work properly.Debugging and associated refactoring and other rework consume about 50 percent of the time on a traditional,naive software-development cycle.
    ——Software projects with the lowest levels of defects had the shortest development schedules and the highest development productivity...Software defect removal is actually the most expensive and time-consuming of work for software.
    ——Compared to the traditional code-test-debug cycle,an enlightened software-quality program saves money.It redistributes resources away from debugging and refactoring into upstream quality-assurance activities.
    ——Not all quality-assurance goals are simultaneously achievable.Explicitly decide which goals you want to achieve,and communicate the goals to other people on your team.
    ——Quality assurance in the software arena is process-oriented.Software development doesn't have a repetitive phase that affects the final product like manufacturing does,so the quality of the result is controlled by the process used to develop the software.

 

    2015-04-09   484   Collaborative Construction
    ——In one way or another,all collaborative construction techniques are attempts to formalize the process of showing your work to someone else for the purpose of flushing out errors.
    问题:什么是合作构建?包含哪些活动?
    ——All collaborative construction techniques,despite their differences,are based on the idea that developers are blind to some of the trouble spots in their work.
    ——Various studies have shown that in addition to being more effective at catching errors than testing,collaborative practices find different kinds of errors thatn testing does.
    ——The need for reviewing was so obvious to the best programmers that they rarely mentioned it in print,while the worst programmers believed they were so good that their work did not need reviewing.
    ——The code,the standards,and the reasons for making the code meet the standards are good topics for review discussions.
    ——Reviews create a venue for more experienced and less experienced programmers to communicate about technical issues.As such,reviews are an opportunity for cultivating quality improvements in the future as much as in the present.
    问题:为什么要强调代码的集体所有权?
    ——Pair programming will not be effective if the two people in the pair spend their time arguing about coding style.Try to standardize the "accidental attributes" of programming so that the programmers can focus on the "essential" task at hand.
    ——Pairs encourage each other to keep code quality high even when there's pressure to write quick and dirty code.

 

    2015-04-10   490   Collaborative Construction
    ——An inspection is a specific kind of review that has been shown to be extremely effective in detecting defects and to be relatively economical compared to testing.
    ——The inspection focuses on defect detection,not correction.
    问题:代码视察中有哪些不同角色?每个角色负责什么任务?
    ——Under no circumstances should inspection results be used for performance appraisals.Evaluation of performance should be based on final products,not on work that isn't finished.
    ——The design or code should speak for itself;the overview shouldn't speak for it.
    ——The scribe notes the type and the severity of the error,and the inspection moves on.If you have problems keeping the discussions focuses,the moderator might ring a bell to get the group's attention and put the discussion back on track.
    ——Some inspection groups don't even allow discussion about whether a defect is really a defect.They assume that if someone is confused enough to think it's a defect,the design,code,or documentation needs to be clarified.
    ——As you do inspections,you'll notice that certain kinds of errors occur more frequently than other kinds.Create a checklist that calls attention to those kinds of errors so that reviewers will focus on them.
    ——The point of the inspection itself is to discover defects in the design or code.It is not to explore alternatives or to debate about who is right and who is wrong.

 

    2015-04-13   495   Collaborative Construction
    ——Acknowledging a criticism doesn't imply that the author agrees with the content of the criticism.
    ——The inspection process is systematic because of its standard checklists and standard roles.It is also self-optimizing because it uses a formal feedback loop to improve the checklists and to monitor preparation and inspection rates.
    ——A Capability Maturity Model that measures the effectiveness of an organization's software-development process-the process is systematic and repeatable and uses measured feedback to improve itself.
    ——Other kinds of collaboration haven't accumulated the body of empirical support that inspections or pair programming have,so they're covered in less depth here.
    问题:代码走查的定义是宽松的,但所有的代码走查都有的共同点有哪些?
    ——Used unintelligently,walk-throughs are more trouble than they're worth.
    ——A review is basically a meeting,and meetings are expensive.If you're going to incur the overhead of holding a meeting,it's worthwhile to structure the meeting as formal inspection.If the work product you're reviewing doesn't justify the overhead of a formal inspection,it doesn't justify the overhead of a meeting at all.
    问题:既然代码视察比走查更高效,为什么要选择代码走查?
    ——If you're choosing a review standard for your organization,choose inspections first unless you have good reason not to.
    ——The difference between code reading on the one hand an inspections and walk-throughs on the other is that code reading focuses more on individual review of the code than on the meetings.
    ——Code readings are especially valuable in situations in which reviewers are geographically dispersed.

 

    2015-04-14   503   Developer Testing
    ——Testing is usually broken into two broad categories:black-box testing and white-box(or glass-box) testing.
    ——Some programmers use the terms "testing" and "debugging" interchangeablly,but careful programmers distinguish between the two activities.
    ——An absence of errors could mean ineffective or incomplete test cases as easily as it could mean perfect software.
    ——If you want to lose weight,don't buy a new scale;change your diet.If you want to improve your software,don't just test more;develop better.
    ——Testing requires you to assume that you'll find errors in your code.If you assume you won't,you probably won't,but only because you'll have set up a self-fulfilling prophecy.
    ——Depending on the project's size and complexity,developer testing should probably take 8 to 25 percent of the total project time.
    ——During construction,you generally write a routine or class,check it mentally,and then review it or test it.Regardless of your integration or system-testing strategy,you should test each unit thoroughly before you combine it with any others.

 

    2015-04-15   510   Developer Testing
    ——A systematic approach to developer testing maximizes your ability to detect errors of all kinds with a minimum of effort.
    ——Design the test cases along with the product.This can help avoid errors in reauirements and design,which tend to be more expensive than coding errors.Plan to test and find defects as early as possible because it's cheaper to fix defects early.
    问题:为什么写测试用例要在写代码之前进行?
    ——Writing test cases first forces you to think at least a little bit about the requirements and design before writing code,which tends to produce better code.
    ——All in all,I think test-first programming is one of the most beneficial software practices to emerge during the past decade and is a good general approach.
    问题:代码语句覆盖率和代码分支覆盖率的区别是什么?
    ——Since exhaustive testing is impossible,practically speaking,the art of testing is that of picking the test cases most likely to find errors.
    ——In spite of the hairy name,structured basis testing is a fairly simple concept.The idea is that you need to test each statement in a program at least once.
    问题:结构化基础测试中,如何计算最小用例数?
    ——Shorter routines tend to have fewer paths to test.Boolean expressions without a lot of ands and ors have fewer variations to test.Ease of testing is another good reason to keep your routines short and your boolean expressions simple.
    ——Data-flow testing is based on the idea that data usage is at least as error-prone as control flow.

    2015-04-20 515 Developer Testing
    ——After you've checked for the anomalous sequences,the key to writing data-flow test cases is to exercise all possible defined-used paths.
    ——A good way to develop test cases is to start with structured basis testing,which gives you some if not all of the defined-used data flows.Then add the cases you still need to have a complete set of defined-used data-fow cases.
    问题:什么是等价类划分?
    ——Equivalence partitioning is especially helpful when you're looking at a program from the outside(from a specification rather than the source code)or when the data is complicated

and the complications aren't all reflected in the program's logic.
    ——Error guessing means creating test cases based upon guesses about where the program might have errors,although it implies a certain amount of sophistication in the guessing.
    ——One of the most fruitful areas for testing is boundary conditions:off-by-one errors.
    问题:典型的坏数据测试包含哪些类型?

    2015-04-21 522 Developer Testing
    问题:典型的好数据测试包含哪些类型?
    ——You might think that an ugly number like $90,783.82 would be more likely to reveal errors,but it's no more likely to than any other number in its equivalence class.
    ——Most errors tend to be concentrated in a few highly defective routines.
    ——Maintenance activities should be focused on identifying,redesigning,and rewriting from the ground up those routines that have been identified as error-prone.
    ——If you see hoof prints,think horses-not zebras.The OS is probably not broken.And the database is probably just fine.
    ——Attention to detail counts.If you doubt that,consider that three of the most expensive software errors of all time involved the change of a single character in a previously correct program.
    ——It's worthwhile to take the time you need to understand the design thoroughly.Such time doesn't produce immediate dividends-you don't necessarily look like you're working-but it pays off over the life of the project.
    ——The better the application area is understood,the better the overall architecture is.Errors then tend to be concentrated in detailed design and coding.
    ——The results of the TSP and cleanroom projects confirm another version of the General Principle of Software Quality:it's cheaper to build high-quality software than it is to build and fix low-quality software.
    ——Test cases tend to be created on the fly rather than through a careful design and construction process.They are often viewed as one-time tests and are developed with the care commensurate with something to be thrown away.

    2015-04-23 527 Developer Testing
    ——Effective plannning for tesing should start at the requirements stage or as soon as you get the assignment for the program.
    ——Having an integrated test framework prevents the tendency,just mentioned,to throw away test cases.
    问题:什么是测试脚手架?
    ——One kind o fscaffolding is a class that's dummied up so that it can be used by another class that's being tested.Such a class is called a "mock object" or "stub object".
    ——Another kind of scaffolding is a fake routine that calls the real routing being tested.This is called a "driver" or,somtimes,a "test harness".
    ——The few minutes that you spend building scaffolding to exercise the deeply buried code can save hours of debugging time.
    ——When you integrate the code,leave the routines and the scaffolding code that exercises them in the file and use preprocessor commands or comments to deactivate the scaffolding code.
    问题:如何使用diff工具简化回归测试?
    问题:使用测试数据生成器有哪些好处?
    ——A coverage monitor is especially useful for systematic testing because it tells you whether a set of test cases fully exercises the code.
    ——A debugger has the capacity to step through code line by line,keep track of variables' values,and always interpret the code the same way the computer does.
    ——Imaginative use of a debugger produces benefits far beyond its initial charter.

    2015-04-24 535 Developer Testing
    问题:有哪些起系统扰动功能的测试工具?
    ——One powerful test tool is a database of errors that have been reported.Such a database is both a management and a technical tool.
    问题:如何改进测试活动?
    ——You have to know exactly what the process does so that you can vary it slightly and observe the effects of the variation.When you observe a change that has a positive effect,you modify the process so that it becomes a little better.
    ——Putting testing on the same level of importance as design or coding means that time will be allocated to it,it will viewed as important,and it will be a high-quality process.
    ——Test automation is part of the foundation of test-intensive practices,such as the daily build and smoke test and Extreme Programming.
    ——In addition to project-level test records,you might find it useful to keep track of your personal test records.
    ——Test-Driven Development:a development approach that's characterized by writting test cases first and then writing the code to satisfy the test cases.
    ——You can generate many test cases deterministically by using basis testing,data-flow analysis,boundary analysis,classes of bad data,and classes of good data.You can generate additional test cases with error guessing.
    ——In the long run,the best way to improve your testing process is to make it regular,measure it,and use what you learn to improve it.

    2015-04-27 539 Debugging
    ——Debugging is twice as hard as writing the code in the first place.Therefore,if you write the code as cleverly as possible,you are,by definition,not smart enough to debug it.
    ——Debugging doesn't have to be the hardest part.If you follow the advice in this book,you'll have fewer errors to debug.
    ——Like testing,debugging isn't a way to improve the quality of your software per se;it's a way to diagnose defects.
    ——The best programmers found the most defects,found the defects most quickly,and made correct modifications most often.You don't have to choose between quality,cost,and time-they all go hand in hand.
    ——If you don't know exactly what you're telling the computer to do,you're only a small step away from merely trying different things until something seems to work-that is,programming by trial and error.
    ——You might be an excellent programmer who has simply made a modest oversight.If this is the case,an error in your program provides a powerful opportunity for you to learn many things.
    问题:从软件缺陷中可以学到哪些东西?
    ——It's not every day that a spotlight exposes a weakness with glaring clarity,but such a day is an opportunity,so take advantage of it.
    ——Considering the amount of time many projects spend on debugging,you definitely won't waste timeif you observe how you debug.Taking time to analyze and change the way you debug might be the quickest way to decrease the total amount of time it takes you to develop a program.
    ——All things considered,debugging is an extraordinarily rich soil in which to plant the seeds of your own improvement.It's where all construction roads cross:readability,design,code quality-you name it.

    2015-04-28 544 Debugging
    ——Old Scratch has agreed to share the lowest circle with programmers who don't learn to debug effectively.
    问题:有哪些错误的调试方法?
    ——Every group has one programmer who has endless problems with demon machines,mysterious compiler defects,hidden language defects that apppear when the moon is full.
    ——The program doesn't do something different every time.It didn't write itself;you wrote it,so take responsibility for it.
    ——It's hard enough to find a defect in your code when you're looking for it;it's even harder when you assume your code is error-free.
    ——Debugging by thinking about the problem is much more effective and interesting than debugging with an eye of a newt and the dust of a frog's ear.
    问题:典型的科学方法包含哪五步?
    问题:定位并修改软件缺陷的有效方法包含哪五步?
    ——The defect is easier to diagnose if you can stabilize it-that is,make it occur reliably.
    ——When you have proven your hypothesis,you fix the defect,test the fix,and search your code for similar errors.
    ——Stabilize the error:if a defect doesn't occur reliably,it's almost impossible to diagnose.Making an intermittent defect occur predictably is one of the most challenging tasks in debugging.
    问题:软件中概率发生的错误有哪些常见的产生原因?
    ——The goal of simplifying the test case is to make it so simple that changing any aspect of it changes the behavior of the error.Then,by changing the test case carefully and watching the program's behavior under controlled conditions,you can diagnose the problem.

    2015-04-29 550 Debugging
    ——If you're having a hard time finding a defect,it could be because the code isn't well written.
    问题:如何精炼猜想?如何精炼测试案例?
    ——Defects tend to be easier to find in small fragments of code than in large integrated programs.Use your unit tests to test the code in isolation.
    ——Errors often arise from combinations of factors,and trying to diagnose the problem with only one test case often doesn't diagnose the root problem.
    ——Rather than limiting yourself to the first hypothesis you think of,try to come up with several.Don't analyze them at first-just come up with as many as you can in a few minutes.
    ——Rather than removing regions haphazardly,divide and conquer.Use a binary search algorithm to focus your search.Try to remove about half the code first time.
    ——Be suspicious of classes and routines that have had defects before.Classes that have had defects before are likely to continue to have defects.
    ——If you're debugging and making no progress,once you've tried all the options,let it rest.Go for a walk.Work on something else.Go home for the day.Let your subconscious mind tease a solution out of the problem.
    问题:什么是“Brute-Force Debugging”,它包含哪些具体方法?
    ——It's always tempting to try for a quick guess rather than systematically instrumenting the code and giving the defect no place to hide.The risk is that if the five-minute approach doesn't work,you get stubborn.
    ——Once you find the real defect,try to determine the reason the compiler put the message on the wrong statement.Understanding your compiler better can help you find future defects.
    ——Some compilers get so excited after detecting the first error that they become giddy and overconfident;they prattle on with dozens of error messages that don't mean anything.

    2015-04-30 556 Debugging
    ——The hard part of debugging is finding the defect.Fixing the defect is the easy part. But as with many easy tasks, the fact that it's easy makes it especially error-prone.
    ——The best way to make your life difficult and corrode the quality of your program is to fix problems without really understanding them.
    ——Hurrying to solve a problem is one of the most time-ineffective things you can do.It leads to rushed judgments, incomplete defect diagnosis, and incomplete corrections.
    ——Relax long enough to make sure your solution is right. Don't be tempted to take shortcuts. It might take more time, but it'll probably take less.
    ——When code is special-cased to work around errors, the special cases become the code's most prominent feature. The code will become increasingly barnacled with special cases.
    问题:为什么不能随机的修改代码直到它看上去能工作?
    ——Before you make a change, be confident that it will work. Being wrong about a change should leave you astonished. It should cause self-doubt, personal reevaluation, and deep soul-searching. It should happen rarely.
    ——Watch for the warning sign: if you can't figure out how to look for similar defects, that's a sign that you don't yet completely understand the problem.
    ——If you're both building code and debugging it, you have to switch quickly between the fluid, creative thinking that goes with design and the regidly critical thinking that goes with debugging. As you read your code, you have to battle the code's familiarity and guard against seeing what you expect to see.
    ——You see what you expect to see and thus overlook differences, like the misspelling of the word "language" in the previous sentence.
    问题:什么是心理学距离?
    ——As you debug, be ready for the problems caused by insufficient psychological distance between similar variable names and between similar routine names. As you construct code, choose names with large differences so that you avoid the problem.
    问题:有哪些调试工具?有哪些不那么明显的调试工具?

   2015-05-06   563   Debugging
    ——Set your compiler's warning level to the highest, pickest level possible, and fix the errors it reports.
    ——Assume that the people who wrote the compiler know a great deal more about your language than you do. If they're warning you about something, it usually means you have an opportunity to learn something new about your language.
    ——Examine the output of an execution profiler to satisfy yourself that your program spends a reasonable amount of time in each area.
    ——An interactive debugger is an outstanding example of what is not needed—it encourages trial-and-error hacking rather than systematic design, and also hides marginal people barely qualified for precision programming.
    ——Regardless of the empirical evidence, the basic argument against debuggers isn't valid. The fact that a tool can be misued doesn't imply that it should be rejected.
    ——The debugger isn't a substitute for good thinking. But, in some cases, thinking isn't a substitute for a good debugger either. The most effective combination is good thinking and a good debugger.
    ——A systematic approach to finding and fixing errors is critical to success. Focus your debugging so that each test moves you a step forward. Use the Scientific Method of Debugging.

    2015-05-07   568   Refactoring
    ——Reality: code evolves substantailly during its initial development. Many of the changes seen during initial coding are at least as dramatic as changes seen during maintenance.
    ——Current approaches are more code-centered, and over the life of a project, you can expect code to evolve more than ever.
    ——If you fix errors with logical duct tape and superstition, quality degrades. If you treat modifications as opportunities to tighten up the original design of the program, quality improves.
    ——If you recognize that evolution during development is an inevitable and important phenomenon and plan for it, you can use it to your advantage.
    ——The key strategy in achieving The Cardinal Rule of Software Evolution is refactoring, which Martin Fowler defines as "a change made to the internal structure of the software to make it easier to understand and cheaper to modify without changing its observable behavior".
    问题:什么是重构?
    问题:哪些情况预示代码需要重构?
    ——Duplicate code sets you up to make parallel modifications—whenever you make changes in one place, you have to make parallel changes in another place.
    ——Even classes that begin life with a cohesive interface can lose their original consistency. Class interfaces tend to morph over time as a result of modifications that are made in the heat of the moment and that favor expediency to interface integrity.
    ——Although case statements are not inherently bad, if you find yourself making parallel modifications to similar case statements in multiple parts of the program, you should ask whether inheritance might be a better approach.
    ——Encapsulation(information hiding) is probably the strongest tool you have to make your program intellectually manageable and to minimize ripple effects of code changes.

    2015-05-08   573   Refactoring
    ——Comments have an important role to play, but they thould not be used as a crutch to explain bad code. The age-old wisdom is dead-on: "Don't document bad code,—rewrite it".
    ——Programmers are notoriously bad at guessing what functionality might be needed someday. "Designing ahead" is subject to numerous predictable problems.
    ——Experts agree that the best way to prepare for future requirements is not to write speculative code; it's to make the currently required code as clear and straightforward as possible so that future programmers will know what it does and does not do and will make their changes accordingly.
    ——If a variable is used for more than one purpose—common culprits are i, j, temp, and x—create separate variables for each usage, each of which has a more specific name.
    ——If a class returns a collection, having multiple instances of the collection floating around can create synchronization difficulties. Consider having the class return a read-only collection, and provide routines to add and remove elements from the collection.
    ——Code is often easiest to read and least error-prone if you exit a routine as soon as you know the return value. The alternative of setting a return value and then unwinding your way through a lot of logic can be harder to follow.

    2015-05-13   580   Refactoring
    ——If a routine is too long, sometimes turning it into a class and then further factorint the former routine into multiple routines will improve readability.
    ——If a routine returns an object, it normally should return the most specific type of object it knows about. This is particularly applicable to routines that return iterators, collections, elements of collections, and so on.
    问题:返回接口还是实现类?
    问题:eclipse提供了那些自动重构功能?
    ——If a class isn't doing much, move its code into other classes that are more cohesive and eliminate the class.
    ——If a class needs to use another class but wants more control over its interface, make the superclass a field of the former subclass and then explose a set of routines that will provide a cohesive abstraction.
    ——If a class exposes every public routine of a delegate class(member class), inherit from the delegate class instead of just using the class.
    ——Use a factory method(routine) when you need to create objects based on a type code or when you want to work with reference objects rather than value objects.
    问题:数据级,语句级,子程序级,类的实现和接口级,系统级各有那些重构方法?
    ——Refactoring is a powerful technique for improving code quality. Like all powerful tools, refactoring can cause more harm than good if misused.
    ——Keep the refactorings small so that you fully understand all the impacts of the changes you make.

    2015-05-14   583   Refactoring
    ——For all but the simplest refactorings, do the refactorings one at a time, recompiling and retesting after a refactoring before doing the next one.
    ——The moral is simple: treat simple changes as if they were complicated.
    ——Refactoring is a powerful technique, but it isn't a panacea and it's subject to a few specific kinds of abuse.
    ——Refactoring refers to changes in working code that do not affect the program's behavior. Programmers who are tweaking broken code aren't refactoring; they're hacking.
    ——If you find yourself in a major refactoring session, ask yourself whether instead you should be redesigning and reimplementing that section of code from the ground up.
    ——Refactoring is subject to the same law of diminishing returns as other programming activities, and the 80/20 rule applies. Spend your time on the 20 percent of the refactorings that provide 80 percent of the benefit.
    ——Refactor when you fix a defect: Use the understanding you gain from fixing a bug to improve other code that might be prone to similar defects.
    ——Is there a section of code that you and everyone else on your team is aftraid of? That's probably an error-prone module. Although most people's natural tendency is to avoid these challenging sections of code, targeting these sections for refactoring can be one of the most effective strategies.

    2015-05-15   587   Refactoring
    ——One classic study found that program quality improved dramatically when maintenance programmers focused their improvement efforts on the modules that had the highest complexity.
    ——Code that is never modified doesn't need to be refactored. But when you do touch a section of code, be sure you leave it better than you found it.
    ——Your code doesn't have to be messy just because the real world is messy. Conceive your system as a combination of ideal code, interfaces from the ideal code to the real world, and the messy real world.
    ——One strategy for improving production code is to refactor poorly written legacy code as you touch it, so as to move it to the other side of the "interface to the messy real world".
    ——Have you avoided using refactoring as a cover for code and fix or as an excuse for not rewriting bad code?
    ——Refactoring during development is the best chance you'll get to improve your program, to make all the changes you'll wish you'd mad the first time. Take advantage of these opportunities during development!

    2015-05-18   590   Code-Tuning Strategies
    ——You can address performance concerns at two levels: strategic and tactical. This chapter addresses strategic performance issues: what performance is, how important it is, and the general approach to achieving it.
    ——More computing sins are commited in the name of efficiency (without necessarily achieving it) than for any other single reason—including blind stupidity.
    ——Some people look at the world through rose-colored glasses. Programmers like you and me tend to look at the world through code-colored glasses. We assume that the better we make the code, the more our clients and customers will like our software.
    ——Be wary of sacrificing other characteristics to make your code faster. Your work on speed might hurt overall performance rather than help it.
    ——Performance is stated as a requirement far more often than it actually is a requirement. Before you invest time solving a performance problem, make sure that you're solving a problem that needs to be solve.
    ——The mere act of making goals explicit improves the likelihood that they'll be achieved. Programmers work to objectives when they know what they are; the more explicit the objectives, the easier they are to work to.

    2015-05-19   595   Code-Tuning Strategies
    ——Achieving a high degree of modifiability can provide a better basis for
meeting efficiency goals than explicitly setting an efficiency target. With a highly modular, modifiable design, you can easily swap less-efficient components for more-efficient ones.
    问题:什么是代码调优?
    ——Code tuning is the practice of modifying correct code in ways that make it run more efficiently. "Tuning" refers to small-scale changes that affect a single class, a single routine, or, more commonly, a few lines of code.
    ——Code tuning is appealing for several reasons. But the problem with code tuning is that efficient code isn't necessarily "better" code.
    ——You should measure the code to find the hot spots and then put your resources into optimizing the few percent that are used the most.
    ——The Pareto Principle is also the source of the advice to write most of the code in an interpreted language like Python and then rewrite the hot spots in a faster compiled language like C.
    ——"The best is the enemy of the good." Working toward perfection might prevent completion. Complete it first, and then perfect it. The part that needs to be perfect is usually small.
    ——Regardless of the aesthetic appeal of writing something with the fewest lines of code, no predictable relationship exists between the number of lines of code in a high-level language and a program's ultimate size and speed.
    ——We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.
    问题:为什么不要在一开始就优化代码效率?
    ——Focusing on ooptimization during initial development detracts from achieving other program objectives. Developers immerse themselves in algorithm ananlysis and arcane debates that in the end don't contribute much value to the user.

    2015-05-19   595   Code-Tuning Strategies
    ——Achieving a high degree of modifiability can provide a better basis for
meeting efficiency goals than explicitly setting an efficiency target. With a highly modular, modifiable design, you can easily swap less-efficient components for more-efficient ones.
    问题:什么是代码调优?
    ——Code tuning is the practice of modifying correct code in ways that make it run more efficiently. "Tuning" refers to small-scale changes that affect a single class, a single routine, or, more commonly, a few lines of code.
    ——Code tuning is appealing for several reasons. But the problem with code tuning is that efficient code isn't necessarily "better" code.
    ——You should measure the code to find the hot spots and then put your resources into optimizing the few percent that are used the most.
    ——The Pareto Principle is also the source of the advice to write most of the code in an interpreted language like Python and then rewrite the hot spots in a faster compiled language like C.
    ——"The best is the enemy of the good." Working toward perfection might prevent completion. Complete it first, and then perfect it. The part that needs to be perfect is usually small.
    ——Regardless of the aesthetic appeal of writing something with the fewest lines of code, no predictable relationship exists between the number of lines of code in a high-level language and a program's ultimate size and speed.
    ——We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.
    问题:为什么不要在一开始就优化代码效率?
    ——Focusing on ooptimization during initial development detracts from achieving other program objectives. Developers immerse themselves in algorithm ananlysis and arcane debates that in the end don't contribute much value to the user.

    2015-05-21   598   Code-Tuning Strategies
    ——If the development time saved by implementing the simplest program is devoted to optimizing the running program, the result will always be a program that runs faster than one developed with indiscriminate optimization efforts.
    ——For a certain class of projects, speed or size is a major concern. This class is the minority, is much smaller than most people think, and is getting smaller all the time.
    ——Jackson's Rules of Optimization: Rule 1. Don't do it. Rule 2 (for experts only). Don't do it yet—that is, not until you have a perfectly clear and unoptimized solution.
    ——Optimizing compilers are better at optimizing straightforward code than they are at optimizing tricky code. If you do "clever" things like fooling around with loop indexes, your compiler has a harder time doing its job and your program suffers.
    ——You always have to profile the program to know with any confidence which parts are slow and fat, but some operations have a long history of laziness and obesity, and you can start by investigating them.

    2015-05-22   609   Code-Tuning Strategies
    ——An operation that causes the operating system to swap pages of memory is much slower than an operation that works on only one page of memory.
    ——Defining an index on a commonly used table is not optimization; it's just good programming practice.
    ——In every case, improving speed comes from replacing an expensive operation with a cheaper one.
    ——Because small parts of a program usually consume a disproportionate share of the runtime, measure your code to find the hot spots. Once you've found the hot spots and optimized them, measure the code again to assess how much you've improved it. Many aspects of performance are counterintuitive.
    ——The only result of optimization you can usually be sure of without measuring performance is that you've made your code harder to read. If it's not worth measuring to know that it's more efficient, it's not worth sacrificing clarity for a performance gamble.
    ——Quantitative measurement is a key to maximizing performance. It's needed to find the areas in which performance improvements will really count, and it's needed again to verify that optimizations improve rather than degrade the software.

    2015-05-25   617   Code-Tuning Techniques
    ——The changes in this chapter might better be called "anti-refactoring". Far from "improving the internal structure," these changes degrade the internal structure in exchange for gains in performance.
    问题:什么是短路赋值?
    ——Arrange tests so that the one that's fastest and most likely to be true is performed first. It should be easy to drop through the normal case, and if there are inefficiencies, they should be in processing the uncommon cases.
    ——In some circumstances, a table lookup might be quicker than traversing a complicated chain of logic. The point of a complicated chain is usually to categorize something and then to take an action based on its category.
    ——Many of the things people feel rushed to do simply don't need to be done. If he waited long enough, the things that weren't important would be procrastinated into oblivion and he wouldn't waste his time doing them.
    ——If a program uses lazy evaluation, it avoids doing any work until work is needed. Lazy evaluation is similar to just-in-time strategies that do the work closest to when it's needed.

 
 
 
原文地址:https://www.cnblogs.com/yuanchongjie/p/4448444.html