"Java Bug mode" Reading notes

Source: Internet
Author: User
Tags stack trace

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 :

    1. Extract the public code.
    2. Compromise between encapsulating code and maintaining a single point of control for each feature element.
    3. 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.
    4. All captured or declared detected exceptions must be thrown, which means that some code in the method cannot be extracted.
    5. 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 :

    1. The code presents a symptom that the previously modified bug seems to still exist.
    2. A bug occurs in a job that has a lot of cut-and-paste code.
    3. A bug is caused by a change in the numeric field type of a class.
    4. The modified method returns a value with a reasonable surface but an actual error after compiling.
    5. Build the Treevisitor interface separately to create a different accept () for each type that you want to return.
    6. 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 :

    1. A NullPointerException exception has occurred, and I don't know what error it represents!
    2. A nullpointerexception exception occurred in code that uses recursion to define the data type.
    3. 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?
    4. Is there a problem when inserting a null pointer into a different type of conforming data?
    5. 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 :

    1. A NullPointerException exception has occurred, and I don't know what error it represents!
    2. 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 :

    1. When the data is recursively visited, the code throws a ClassCastException exception.
    2. When a recursive next visit to the data, in a recursive call occurred in a multilevel down.
    3. Is there a problem creating multiple different instances of the same class?
    4. Use instanceof and equals to examine the identifiers of classes and objects; Is there a better way?
    5. What can I do to eliminate the 0 value in a continuous node?
    6. The code cannot be dispatched properly after a method call has been made.
    7. 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?
    8. Why do you need to annotate all invariants in your code?
    9. 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 :

    1. Is there an exception in GUI design?
    2. The GUI passed all the tests, but now the customer called and told me there was a problem. What is the reason for this?
    3. Unit testing is really a good way to assist with debugging, but is it really necessary to write so many unit tests?
    4. Why does the test and code run the behavior mismatch?
    5. Tests and code run without consistent results. Is the test wrong?
    6. How does the GUI test work?
    7. Are there possible errors in the model-view controller (MVC) structure in your program?
    8. Is there an optimal time to check the model through the view?
    9. If you can't easily implement an automated test GUI, how can you use tests to check your code?
    10. Should a continuous refactoring method be used?
    11. Are there other key elements for effective, permanent refactoring of your code?
    12. The Java robot class is said to be effective for GUI testing. Does it work for each instance?
    13. 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 :

    1. The data entry code could have worked fine, but after a while, the same task collapsed. Where is the problem?
    2. The data that caused the crash comes from large data structures on the network. Is this the problem?
    3. What are the possible reasons for data corruption-syntactic or semantic parts?
    4. What can cause data corruption--manually editing or automatically generating files?
    5. 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?
    6. Does type checking help to semantically identify corrupted data?
    7. What can I do with the existing data if the data cannot be checked at the time of input?
    8. Does iterating over data be an effective way to clean up corrupted data? Under what circumstances?
    9. Should you iterate over the data and access all the data (just like in a deployed application)?
    10. Is it always possible to find the corrupted data before it causes a problem? If not, why?
    11. 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 :

    1. I overloaded a method, and then another method broke down. What does that mean?
    2. Is it possible because the method parameters do not match?
    3. Does adding a new method cause an interruption of other methods?
    4. What happens if a generic method's constructor overloads a more special method?
    5. 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 :

    1. Why does the program treat different types of data as the same type?
    2. The code does not recognize some data types.
    3. Is there a problem with using tags to differentiate data types in special fields?
    4. Why should a static type system be used to differentiate data types?
    5. 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 :

    1. The code has a memory leak. What are the possible causes?
    2. Why do programs release resources prematurely (such as database connections)?
    3. Should resources be obtained and freed in the same method to release resources?
    4. Should you keep track of each path that your code might execute in order to ensure that resources are released?
    5. Why do some code execution paths not release resources at once at the relevant time?
    6. Should you anticipate and write code for all the ways programs might extend?
    7. 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 :

    1. How to formally define interfaces?
    2. When implementing an interface, why does the client class responsible for handling this interface happen to have a terminal?
    3. Is it possible to not explicitly record invariants in an interface?
    4. What are the flaws when loading code with other invariants?
    5. As a security guarantee, should I specify invariants that can be checked all statically?
    6. Can I limit the definition of interface invariants to type signing?
    7. What is an assertion? Are there different types of assertions?
    8. Where should assertions be included in the interface implementation scenario?
    9. Does including assertions seriously increase the overhead of program execution?
    10. Is the assertion sufficient to capture all the rules I want to define on the interface?
    11. Can I use unit tests to provide restriction specifications for other interface invariants?
    12. is the unit test set capable of detecting all the inputs in the implementation scenario?
    13. 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 :

    1. The multithreaded code is locked and it prints the stack trace to a standard error.
    2. What if a single-threaded design is used?
    3. Is there a problem with the Stop () method on the thread?
    4. 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 :

  1. A NullPointerException exception has occurred, and I don't know what error it represents!
  2. A NullPointerException exception occurs when a field that is not initialized is accessed.
  3. Not all fields in the class are initialized. Is the constructor not built correctly?
  4. Is there a problem with requiring the client class to initialize the instance's constructors in multiple steps?
  5. A class has added new fields more than once. Is it possible to add a field that might cause incorrect initialization?
  6. Does the execution order of the statements affect the program?
  7. Should the customer be persuaded to throw away the old code and rewrite the new code?
  8. If you are using legacy code. Can I modify the constructor signature?
  9. What is the best way to control NullPointerException exception errors when using old code?
  10. What is the effect of using the isinitialized () method in a class?
  11. How do I ensure that an instance of a class is in a properly defined state?
  12. Would it help if the class field was populated with null values?
  13. What is a quick way to ensure that an instance has been initialized?
  14. How do I avoid initializing bugs in the new context?
  15. What is the best way to represent a default value?
  16. Do you use a special class to indicate whether the default value will cause performance degradation? If yes, why?
  17. Is it possible to perform a direct initialization check without performing a type conversion at run time, without causing performance degradation?
  18. 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 :
    1. Why does the code only run on some Java virtual machines and not on other machines?
    2. Why does the code only run on some versions of the JVM and not on other versions?
    3. Why is the code only running on some operating systems and not running on other operating systems?
    4. What is the difference between a specification-related bug and a bug that is related to an implementation scenario?
    5. 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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.