bug patterns are recurring correlations between bugs that have occurred in a program and potential bugs. With this knowledge of patterns and bug phenomena, programmers can quickly identify new bugs and prevent them from happening.
the bug pattern is related to anti-pattern, which refers to the common design pattern of software that has been proved to be a failure many times. The reverse example of these designs is a necessary complement to the traditional façade design pattern. Although anti-patterns are also a design pattern, bug patterns are an incorrect program behavior pattern associated with programming errors. This relationship is irrelevant to the design, but is related to writing code and debugging procedures.
The following is a detailed understanding of bug patterns in 13.
1.Rogue Tile Mode
causes : this is usually caused by copying and pasting code snippets between different parts of the program.
symptom : After you have corrected the code that caused the error behavior, the program continues to have an error.
Solutions & Preventative measures :
- Extract the public code.
- Compromise between encapsulating code and maintaining a single point of control for each feature element.
- The static type language restricts the expression of the language, thus reducing the effect of preventing rogue tiles. A common type can compensate for this flaw in the Java language to some extent.
- All captured or declared detected exceptions must be thrown, which means that some code in the method cannot be extracted.
- Aspect-oriented programming techniques--by adding "facet (aspect)" to the program's classes and functions to organize the program--helps to process the copied code (each aspect corresponds to the global properties of the program, for example, how to handle the checked exception in the method).
Diagnostic Checklist :
- The code presents a symptom that the previously modified bug seems to still exist.
- A bug occurs in a job that has a lot of cut-and-paste code.
- A bug is caused by a change in the numeric field type of a class.
- The modified method returns a value with a reasonable surface but an actual error after compiling.
- Build the Treevisitor interface separately to create a different accept () for each type that you want to return.
- At run time, although the same Treevisitor interface is used for everything, and the type conversion is inserted at each visitor method invocation, the result is a classcastexception exception.
2.Dangling Composite Mode
cause : A null pointer exception is reported in code that uses a recursive definition of the data type.
Symptom : When you define a recursive data type, you do not define the class to which it belongs for some basic types. Therefore, the null pointer is inserted into the various composite data types. The client code then handles the basic types in a inconsistent manner.
Workaround & Precautions : To ensure consistency, make sure that the base types are correctly represented and inspected, and that each base type is assigned its own class.
Diagnostic Checklist :
- A NullPointerException exception has occurred, and I don't know what error it represents!
- A nullpointerexception exception occurred in code that uses recursion to define the data type.
- Is there a problem when defining a recursive data type, so that some of the basic types do not determine what class they belong to?
- Is there a problem when inserting a null pointer into a different type of conforming data?
- Go out to the leaf class and use the leaf node to control the left and right fields in the branch to see if the classcastexception exception can be repaired and to reduce the type conversion operation?
3.Null Flag Mode
cause : The calling method is not checked for a null pointer as the return value.
symptom : A nullpointerexception is reported with a code snippet that uses a null pointer as an exception condition flag.
Workaround & Precautions : report exception conditions by throwing exceptions.
Diagnostic Checklist :
- A NullPointerException exception has occurred, and I don't know what error it represents!
- Go out to the leaf class and use the leaf node to control the left and right fields in the branch to see if the classcastexception exception can be repaired and to reduce the type conversion operation?
4.Double descent mode
cause : Part of the code accesses the two layer down in each method call and is improperly dispatched the second time.
Symptom : The program throws a Classcassexceptions exception in the recursive execution of the data structure.
Workaround & Precaution : Break down the code that enforces type conversions into a separate method for each class. Another option is to check the invariants to ensure that the type conversions are enforced successfully.
Diagnostic Checklist :
- When the data is recursively visited, the code throws a ClassCastException exception.
- When a recursive next visit to the data, in a recursive call occurred in a multilevel down.
- Is there a problem creating multiple different instances of the same class?
- Use instanceof and equals to examine the identifiers of classes and objects; Is there a better way?
- What can I do to eliminate the 0 value in a continuous node?
- The code cannot be dispatched properly after a method call has been made.
- Go out to the leaf class and use the leaf node to control the left and right fields in the branch to see if the classcastexception exception can be repaired and to reduce the type conversion operation?
- Why do you need to annotate all invariants in your code?
- What are the drawbacks of using instanceof checks to avoid classcastexception exceptions?
5.Liar view mode
cause : The test just examines the different aspects of the model directly.
symptoms : The GUI program passes the test set, but then shows the behavior that should have been eliminated in those tests.
Workaround & Preventative measures : write independent test programs for models and views based on overall testing.
Diagnostic Checklist :
- Is there an exception in GUI design?
- The GUI passed all the tests, but now the customer called and told me there was a problem. What is the reason for this?
- Unit testing is really a good way to assist with debugging, but is it really necessary to write so many unit tests?
- Why does the test and code run the behavior mismatch?
- Tests and code run without consistent results. Is the test wrong?
- How does the GUI test work?
- Are there possible errors in the model-view controller (MVC) structure in your program?
- Is there an optimal time to check the model through the view?
- If you can't easily implement an automated test GUI, how can you use tests to check your code?
- Should a continuous refactoring method be used?
- Are there other key elements for effective, permanent refactoring of your code?
- The Java robot class is said to be effective for GUI testing. Does it work for each instance?
- Can the non-GUI data display software also show the difference between test and run time results?
6.Saboteur Data Mode
cause : Some internal data is corrupted, possibly grammatical or semantic.
Symptom : A program used to store and process complex input data crashes unexpectedly while performing a task, while performing other similar tasks with no problem.
Workaround & Precautions : Make as many integrity checks as possible on the input data, and the sooner the better. For persistent data that has been corrupted, study the data and check its integrity.
Diagnostic Checklist :
- The data entry code could have worked fine, but after a while, the same task collapsed. Where is the problem?
- The data that caused the crash comes from large data structures on the network. Is this the problem?
- What are the possible reasons for data corruption-syntactic or semantic parts?
- What can cause data corruption--manually editing or automatically generating files?
- It seems like a big project to analyze the data to check if the data has been destroyed! Isn't this the job that the compiler should do?
- Does type checking help to semantically identify corrupted data?
- What can I do with the existing data if the data cannot be checked at the time of input?
- Does iterating over data be an effective way to clean up corrupted data? Under what circumstances?
- Should you iterate over the data and access all the data (just like in a deployed application)?
- Is it always possible to find the corrupted data before it causes a problem? If not, why?
- Does dividing a line of text into two strings cause hard-to-find, corrupted data?
7.Broken Dispatch mode
cause : The overloaded procedure enables an unmodified method to activate another method, rather than the method you want to invoke.
symptom : After overloading another method, an error occurs when you test code that has never been modified.
Workaround & Precautions : Insert an explicit up-type cast, or reconsider the set of methods that are available in different classes.
Diagnostic Checklist :
- I overloaded a method, and then another method broke down. What does that mean?
- Is it possible because the method parameters do not match?
- Does adding a new method cause an interruption of other methods?
- What happens if a generic method's constructor overloads a more special method?
- Should the test be "full" in my Code?
8.Impostor type mode
cause : The program uses tagged fields for various types of data, rather than separate classes.
Symptom : The program handles different types of data in the same way, or the data does not match any of the specified types.
Workaround & Precaution : Divide conceptually different data types into separate classes as much as possible.
Diagnostic Checklist :
- Why does the program treat different types of data as the same type?
- The code does not recognize some data types.
- Is there a problem with using tags to differentiate data types in special fields?
- Why should a static type system be used to differentiate data types?
- To avoid type mismatches, the following workaround is used: Use the If-then-else statement module to schedule the appropriate type. Does this approach work?
9.Split Cleaner Mode
cause : Some of the program's execution paths do not do what they should do: The program failed to release resources at the right time.
Symptom : The program fails to manage resources properly, but instead leaks or releases these resources prematurely.
Workaround & Precaution : Move the code responsible for freeing resources to the same method that gets the resources.
Diagnostic Checklist :
- The code has a memory leak. What are the possible causes?
- Why do programs release resources prematurely (such as database connections)?
- Should resources be obtained and freed in the same method to release resources?
- Should you keep track of each path that your code might execute in order to ensure that resources are released?
- Why do some code execution paths not release resources at once at the relevant time?
- Should you anticipate and write code for all the ways programs might extend?
- If you find that the execution path does not include the correct release code, should you add code that frees the resource to this path?
10.Fictitious Implementation Mode
cause : The interface includes a number of invariants that the implementation scheme cannot satisfy.
Symptom : When you use a particular implementation of an interface, the client class that handles this interface is interrupted.
Workaround & Preventative measures : Modify the interface implementation scheme to include these invariants. If these invariants have not yet been written to the interface document, they are clearly stated therein.
Diagnostic Checklist :
- How to formally define interfaces?
- When implementing an interface, why does the client class responsible for handling this interface happen to have a terminal?
- Is it possible to not explicitly record invariants in an interface?
- What are the flaws when loading code with other invariants?
- As a security guarantee, should I specify invariants that can be checked all statically?
- Can I limit the definition of interface invariants to type signing?
- What is an assertion? Are there different types of assertions?
- Where should assertions be included in the interface implementation scenario?
- Does including assertions seriously increase the overhead of program execution?
- Is the assertion sufficient to capture all the rules I want to define on the interface?
- Can I use unit tests to provide restriction specifications for other interface invariants?
- is the unit test set capable of detecting all the inputs in the implementation scenario?
- Which is more descriptive for type signing and unit testing?
11.Orphaned thread mode
cause : Multiple program threads are waiting for input from a thread, and the thread exits the program after throwing an exception that is not caught.
Symptom : A multithreaded thread is locked and can or cannot print a stack trace to a standard error.
Workaround & Precautions : Place exception handling code in the main thread to tell other threads that depend on the thread that an exception has occurred. Another way is to put the handler in the exited thread so that it passes the relevant information to its client.
Diagnostic Checklist :
- The multithreaded code is locked and it prints the stack trace to a standard error.
- What if a single-threaded design is used?
- Is there a problem with the Stop () method on the thread?
- In what type of programming are you more likely to encounter an abandoned 2nd thread?
12.run-on initializatier Mode
cause : The constructor of a class does not directly initialize all fields.
symptom : A NullPointerException exception was thrown at the access to the uninitialized field.
Workaround & Precaution : Initialize all fields in one constructor. Use a special class as the default value when there is no better value to use. For cases where a better value can be used, include more than one constructor. When constrained by other factors, include at least one isinitialized () method.
Diagnostic Checklist :
- A NullPointerException exception has occurred, and I don't know what error it represents!
- A NullPointerException exception occurs when a field that is not initialized is accessed.
- Not all fields in the class are initialized. Is the constructor not built correctly?
- Is there a problem with requiring the client class to initialize the instance's constructors in multiple steps?
- A class has added new fields more than once. Is it possible to add a field that might cause incorrect initialization?
- Does the execution order of the statements affect the program?
- Should the customer be persuaded to throw away the old code and rewrite the new code?
- If you are using legacy code. Can I modify the constructor signature?
- What is the best way to control NullPointerException exception errors when using old code?
- What is the effect of using the isinitialized () method in a class?
- How do I ensure that an instance of a class is in a properly defined state?
- Would it help if the class field was populated with null values?
- What is a quick way to ensure that an instance has been initialized?
- How do I avoid initializing bugs in the new context?
- What is the best way to represent a default value?
- Do you use a special class to indicate whether the default value will cause performance degradation? If yes, why?
- Is it possible to perform a direct initialization check without performing a type conversion at run time, without causing performance degradation?
- Some people think that the right way to do this is to include a method that always throws an exception, but does it look too clumsy?
13.platform-dependent mode
13.1 Vendor-related bug patterns
cause : Some content in the JVM specification has not been specified, for example, the optimization of a tail call is not required. This type of bug is relatively small compared to version-related bugs.
symptoms : Some JVMs have bugs, but not on other JVMs.
Workaround & Precautions : Varies by issue.
13.2 version-related bug patterns
cause : caused by bugs in certain versions of a particular vendor JVM. This type of bug is more common than vendor-related bugs.
Symptom : Some versions of the JVM may have bugs, but other versions do not.
Workaround & Precautions : Varies by issue.
13.3 operating system-related bug patterns
cause : System behavior rules may vary in different operating systems. For example, in Unix, you can delete a file that is already open, but not on Windows.
Symptoms : Some operating systems may appear, but other operating systems do not.
Workaround & Precautions : Varies by issue.
Diagnostic Checklist :
- Why does the code only run on some Java virtual machines and not on other machines?
- Why does the code only run on some versions of the JVM and not on other versions?
- Why is the code only running on some operating systems and not running on other operating systems?
- What is the difference between a specification-related bug and a bug that is related to an implementation scenario?
- Is there a comprehensive description of the bugs caused by Java specifications and implementation scenarios?
14. Design mode for debugging
14.1 Maximizing static type checking
1. Design final fields as much as possible.
2. The method that cannot be rewritten is set to final.
3, include the class as the default value.
4, check the abnormal situation, to ensure that all the client program can handle the abnormal situation.
5. Define a new exception type to accurately distinguish the various anomalies.
6. This class is interrupted when an instance of a class uses a state or a fixed number of States for different subclasses in the composite hierarchy.
7. Clear all actions that may involve platform affinity.
8. Test on as many platforms as possible.
9. Minimize the type conversion and instanceof test.
10, using singleton design mode to help minimize the role of instanceof.
11, the use of additional methods and dynamic scheduling to help minimize the role of instanceof.
14.2 minimize the possibility of introducing bugs
1, extract the general code.
2, as far as possible to achieve a pure functional method.
3. Initialize all fields in the constructor.
4. Throws an exception immediately after an abnormal condition occurs.
5. Immediately report an error message when an error occurs.
6, through the grammar analysis, type checking and so on early detection of bugs.
7. Place assertions in your code through the type conversion, Asserttrue () method, document, and document form parameters.
8, as far as possible in the user-observable state of the test code.
Using the above principles will help reduce the likelihood of bugs in your code. You may find that some of the bug patterns discussed here are not the ones that most often appear, and frankly, many of the bug patterns discussed in this book are more problematic, and don't expect to eliminate these bugs once and for all. We can only learn to diagnose them faster and use the right precautions to clear them.
"Java Bug mode" Reading notes