Java Theory and Practice: eliminating bugs

Source: Internet
Author: User
Tags thread

A lot of the advice about programming style is to create high-quality, maintainable code, which is reasonable, because the easiest time to fix bugs is before a bug is created (a small amount of precautions ...). )。 Unfortunately, only prevention is often not enough, although there are some ingenious tools to help you create good code, but few tools can help you analyze, maintain, or improve the quality of your existing code.

It is difficult to write thread-safe classes, but it is more difficult to analyze the thread security of existing classes, and the enhanced classes keep them still thread-safe. With implicit assumptions, invariant, and expected use cases (although clear in the developer's mind, but after writing a class without having to write notes, notes, or documents in a way, people quickly no longer understand how the class works (or how it should work), and the existing code is always harder to use than the new code.

Requirements: Better code auditing tools

Of course, the best time to ensure high quality code is when you're writing code, because you know best how it is organized during this time. There are many suggestions on how to write high quality code (read this column!) , but it may not be possible to write all the code from scratch or spend a lot of time writing it. So what should we do in this situation? Developers often prefer to rewrite code (after all, writing new code is much more interesting than fixing someone else's code or fixing the code they wrote but a lot of bugs), but it's also a luxury, and usually simply swapping today's known errors with the unknown tomorrow. What you need is a tool that analyzes and audits an existing code base to help developers conduct code audits and find bugs.

I am pleased to say that with the introduction of FindBugs, significant progress has been made in automatic code detection and auditing tools. So far, most testing tools either try hard to prove that the program is correct, or focus on some superficial problems, such as code formatting and naming rules, and at most, some simple bug patterns, such as a self assignment, unused domain, or potential error (such as unused method parameters, or A method that can be declared private or protected is declared as public. But unlike FindBugs, it uses bytecode analysis and many built-in bug pattern detectors to find common bugs in your code. It can help you find out where your code is intentionally or unintentionally deviating from good design principles. (For an introduction to FindBugs, see Chris Grindstaff's article, "FindBugs, part 1th: Improving code Quality" and "FindBugs, part 2nd: Writing custom detectors.") )

Design recommendations and bug patterns

For each bug pattern, there are corresponding preventative elements in the design recommendations that warn us to avoid this bug pattern. So if FindBugs is a bug pattern detector, it can be used as an audit tool to measure how well the code fits into a set of design principles. Many of the articles in Java theory and practice specifically describe the specific elements of the design recommendations (or the corresponding bug patterns). In this issue, I will explain how FindBugs ensures that the existing code base follows design recommendations. Let's repeat some of the previous recommendations in a new way and see how FindBugs can help detect when these recommendations are not adhered to.

An argument about the anomaly

In "Java Theory and Practice: an argument about anomalies," one argument against censorship anomalies is that "groping" (that is, capturing) is too easy, and it neither takes corrective action nor throws other exceptions, as shown in Listing 1. In prototyping, sometimes this "groping" is often done simply to compile the program, write an empty catch block, and then return and populate some sort of error-handling strategy later. While some people have given the frequency of this scenario as an example to illustrate the difficulty of handling exceptions to the Java language design, I think it's just a mistake to use the right tool. FindBugs can easily detect and mark these empty catch blocks. If you want to ignore this exception, you can easily add a descriptive comment to the exception so that the reader knows that you deliberately ignore it, rather than simply forgetting to handle it.

Listing 1. "Groping" the anomaly

try {
  mumbleFoo();
}
catch (MumbleFooException e) {
}

Hash

In "Java Theory and Practice: hashing," I outlined the basic rules for correctly overloading Object.Equals () and Object.hashcode (), especially the hashcode () values of equal objects (based on equals ()) must be equal. Even if you understand this rule, it's fairly straightforward to follow (and some Ides contain wizards to define the two methods in a consistent fashion), but if you overload one of these methods and forget to overload another, it's hard to find bugs by instrumentation because the error is not in the code that exists. Instead, it is in the nonexistent code.

FindBugs has a detector that detects many instances of this problem, such as overloading equals () without overloading hashcode (), or overloading hashcode () without overloading equals (). These detectors are the simplest of FindBugs because they only need to check the set of method signatures in the class and determine whether Equals () and hashcode () are overloaded at the same time. You may also incorrectly define equals () with parameter types other than Object, although this construct is legal, but its behavior is different from what you think. The covariant Equals detector detects the following problematic overloads:

public void boolean equals(Foo other) { ... }

Related to this detector is the confusing method Names detector, which is triggered by methods with names similar to Hashcode () and ToString (), which trigger the detector for the following classes: There are some methods that differ only in the case of names, Or the method is the same as the name of the superclass constructor. Although these method names are legitimate according to the specification of the language, they may not be what you want. Similarly, if the domain serialversionuid is not final, not long or static, the serialization detector is triggered.

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.