Destroy annoying bugs part 2: Plug me into Eclipse.

Destroy annoying bugs part 2: Plug me into Eclipse.


Static code reviews aimed at eating bugs (!) are unbiased and neutral. If you spill coffee on their laps or are applying for the same job as them, the advice given back will remain the same. Static code reviews work via rules; some rules are accurate in their assessment and others are not so relevant--or even false. Before building a thorough infrastructure for large-scale deployment, it is well worth installing the tool's respective plugins. You can have a lot of fun kicking the tires of the rule sets for your own particular environment. Getting your fingers into the reality of the code is the first step in the path to Quality Assurance enlightenment. Note to self, remember to ask boss for pay rise.

Note: this is Part 2. Feel free to read Part 1!

Did I also mention the satisfaction involved when splattering bugs?

Assumptions

The examples in this article have been run both on Ubuntu 7.10 and (sorry to say) Windows Vista. PMD and FindBugs are platform agnostic and require Java 1.5 to run. PMD reads the source code and works with most versions of Java. FindBugs uses BCEL to read the meta information from class files, and can therefore read any versions of compiled code. The relevant links are:

TFTP

One of the easiest places to start learning is through visual feedback from within the Eclipse IDE, The Test Performance Tools Platform (TFTP), a top-level eclipse project, has an inbuilt static code review functionality. At the time of writing TFTP includes 72 helpful definitions. For most Eclipse installations you will need to use the usual update mechanism: Help→software updates.

To analyse the code, right click on any piece of code in the Package explorer window, as described in figure 1, and select the Analysis→Open Analysis dialog. The dialog is obvious. Select the project you want analyzed and the rule sets you wish to activate. Finally, press the Analysis button.

Figure 1, shows the main screen of the default Java perspective after analyzing a deliberately weak piece of code. If you click on the green flag on the left-hand side of the source code dialog, you will find an option (or options) to quick fix the selected issue.

Figure 1:  The TFTP framework in actionFigure 1: The TFTP framework in action

Roll up, roll up, and watch the magic of static code analysis at work. Listing 1 is the original code. With untrained eyes and time constraints, you may well miss the fact that name.equals() will always throw a runtime exception and that String constants are hidden in the code rather than concentrated at the top of the class.

public class EvenCleverPeople {
    public static void main(String[] args) {
        String name=null;
        if (name.equals("Admin")){
            System.out.println("Hi special user");
        }
    }
}

Listing 1: Code gone bad

Analyzing and quick fixing via the TFTP framework transforms the code to a stable (and maintainable) listing 2. I particularly like the ADMIN.equals(name) as ADMIN excellently describes the constant and never inconveniently throws a nullpointer exception: at worst it only returns a Boolean false.

public class EvenCleverPeople {
    private static final String ADMIN = "Admin";
    private static final String CONSTANT = "Hi special user"; //$NON-NLS-1$

    public static void main(String[] args) {
        String name=null;
        if (ADMIN.equals( name )){
            System.out.println(CONSTANT);
        }
    }
}

Listing 2: More maintainable and less runtime prone code

If you are not sure of a rule, you should run the "quick fix" procedure: it's a brilliant way to learn; plus, the actions in most cases are sensible and help form good habits. (No, I do not have any bad habits!) At the time of writing 72 rules exist; this is a somewhat more limited subset than either PMD or FindBugs.

FindBugs

The quality of the rules are consistent between the three projects. However, if I had to vote I would consider that FindBugs generates fewer false positives than the rest. Better still, FindBugs finds a few of the more painful gotchas, especially at the high priority levels, and in particular for the correctness category. I strongly suspect that all the tools are strong and have real meaning within a well-balanced development ecosphere.

To install Findbugs please use the usual Help→Software updates section; the site for updates is:

http://findbugs.cs.umd.edu/eclipse-candidate

To activate FindBugs, again right click on a project in the Package explorer dialog. A Find bugs option will appear. Choose FindBugs→FindBugs. Within a very short period of time the code is analyzed and the issues are marked with an attractive bug-like icon. The bug is ready now to be hit with a large stone. I do like the squelchy noise very much: one less potential phone call. Right clicking on the icon and then selecting Show Bug Descriptions brings up the definition of the issue, as shown in figure 2.

The bug is ready now to be hit with a large stone. I do like the squelchy noise very much

Figure 2: FindBugs making bad habits obviousFigure 2: FindBugs making bad habits obvious

PMD

The PMD plugin is also installable via the Help→Software updates option. The site you will need to add is:

http://pmd.sf.net/eclipse

PMD works exactly as expected: after installing it, right click on the package explorer on the relevant project of choice and then select PMD→Check Code with PMD. For our example code, a wide set of bug pattern potential issues are flagged. To generate an HTMLized report, as shown in figure 3, select PMD→Generate Reports.

Figure 3: HTML ReportingFigure 3: HTML Reporting

Another powerful extra included with the PMD installation is its ability to find code that has been copied from elsewhere in the project. Copied code (or "duplicated code"), especially for object orientated languages, is a sign of the need to refactor. Refactoring, for example, by pulling the copied code into a utility or parent class.

Copied code, sorry duplicated code, especially for object orientated languages, is a generic sign of the need to refactor

Conclusion

In summary, each tool is a significant help in the fight for code quality. TFTP has the very handy quick fix option and FindBugs has a very accurate and wide ranging set of rules and workflow. PMD has a wide range of rules, report generation and the ability to spot code duplication. I see the combination of PMD, FindBugs and TFTP much stronger together than as individual Eclipse extensions.

In the next article I will briefly introduce you to the command line use of FindBugs, useful in large scale projects. Better still, I will also interview Professor Bill Pugh, one of the main driving forces behind FindBugs.

Acknowledgments

I would like to thank my wife Hester vander Heijden for at least trying to rewrite some of my known issues, and the Eclipse, FindBugs and PMD teams for building such excellent products.

Category: 

Comments

duhrer's picture
Submitted by duhrer on

The project is actually TPTP and not TFTP(a separate and commonly used acronym). The article is otherwise very useful and timely, thanks much to Alan for his work in this area.

Author information

Alan Berg's picture

Biography

Alan Berg Bsc. MSc. PGCE, has been a lead developer at the Central Computer Services at the University of Amsterdam for the last eight years. In his spare time, he writes computer articles. He has a degree, two masters and a teaching qualification. In previous incarnations, he was a technical writer, an Internet/Linux course writer, and a science teacher. He likes to get his hands dirty with the building and gluing of systems. He remains agile by playing computer games with his kids who (sadly) consistently beat him physically, mentally and morally.

You may contact him at reply.to.berg At chello.nl

Most forwarded

Interview with Dave Mohyla, of DTIDATA

Dave Mohyla is the president and founder of dtidata.com, a hard drive recovery facility based in Tampa, Florida.

TM: Where are you based? What does your company do?
DTI Data recovery is based in South Pasadena, Florida which is a suburb of Tampa. We have been here for over 10 years. We operate a bio-metrically secured class 100 clean room where we perform hard drive recovery on all types of hard disks, from laptop hard drives to multi drive RAID systems.

Anybody up to writing good directory software?

Since the very beginning, directories (of any kind) have had a very central role in the internet. (I have recently grown fond of Free Web Directory. Even Slashdot can be considered a directory: a collection of great news and invaluable user-generated comments. As far as software is concerned, doing a quick search on Google about software directories will return the free (as in freedom) software directories like Savannah, SourceForge, Freshmeat and so on, followed by shareware and freeware sites such as FileBuzz, PCWin Download Center and All Freeware (great if you're looking for shareware and freeware, but definitely less comprehensive than their free-as-in-freedom counterparts).

Interview with Mark Shuttleworth

Mark Shuttleworth is the founder of Thawte, the first Certification Authority to sell public SSL certificates. After selling Thawte to Verisign, Mark moved on to training as an astronaut in Russia and visiting space. Once he got back he founded Ubuntu, the leading GNU/Linux distribution. He agreed on releasing a quick interview to Free Software Magazine.

Is better education the key to finding better software?

I read David Jonathon's article Anybody Up To Writing Good Directory Software? the other day, which got me thinking about software directories in general. As David mentioned, many of the software directories one finds when doing a quick google search are free as in beer, not as in freedom. But what interests me is the software directories that already exist, providing a combination of both free as in beer software, and open source software. Sites such as Freeware Downloads and Shareware Download don't advertise themselves as providing free as in liberty software, but each of them have a good selection of open source software available... if you know where to look.

Most emailed

Free Open Document label templates

If you’ve ever spent hours at work doing mailings, cursed your printer for printing outside the lines on your labels, or moaned “There has got to be a better way to do this,” here’s the solution you’ve been looking for. Working smarter, not harder! Worldlabel.com, a manufacture of labels offers Open Office / Libre Office labels templates for downloading in ODF format which will save you time, effort, and (if you want) make really cool-looking labels

Creating a user-centric site in Drupal

A little while ago, while talking in the #drupal mailing list, I showed my latest creation to one of the core developers there. His reaction was "Wow, I am always surprised what people use Drupal for". His surprise is somehow justified: I did create a site for a bunch of entertainers in Perth, a company set to use Drupal to take over the world with Entertainers.Biz.

Update: since writing this article, I have updated the system so that the whole booking process happens online. I will update the article accordingly!

So, why, why do people and companies develop free software?

More and more people are discovering free software. Many people only do so after weeks, or even months, of using it. I wonder, for example, how many Firefox users actually know how free Firefox really is—many of them realise that you can get it for free, but find it hard to believe that anybody can modify it and even redistribute it legally.

When the discovery is made, the first instinct is to ask: why do they do it? Programming is hard work. Even though most (if not all) programmers are driven by their higher-than-normal IQs and their amazing passion for solving problems, it’s still hard to understand why so many of them would donate so much of their time to creating something that they can’t really show off to anybody but their colleagues or geek friends.

Sure, anybody can buy laptops, and just program. No need to get a full-on lab or spend thousands of dollars in equipment. But... is that the full story?

Fun articles

Santa Claus - the most successful open source project

It dawned on me the other day, as I was shopping for the dozens of gifts it seems I have to buy every December, that Santa Claus is the most successful open source project in history. (Bridget @ Illiterarty would agree with that). Santa Claus is essentially a marketing development that is embodied by everyone who stuffs a sock, gives a gift, hosts a dinner or wishes Merry Christmas over the holiday season.

Most emailed

Editorial

When I first started thinking about Free Software Magazine, I was feeling enthusiastic about the dream. I had Dave, Gianluca, and Alan willing to help me, I had established members of the free software community willing to help me out, I had writers volunteering their time and energy for free, and I had a generous offer from OpenHosting for servers, all before I'd proved myself. There was a sense of excitement in the air, and I thought maybe, just maybe, I could make this work.

Free Software Magazine uses Apollo project management software and CRM for its everyday activities!