Improve your Java code quality

Improve your Java code quality

By delivering a high quality code you will lower the maintenance cost of the system.

The tools presented in this article are intended to help the programmer to improve the code quality of the software by indicating problem areas.

This article only serves to help users to find the problems that can be found when building the code, not how to solve them. Knowing that you have a problem is just the first step. This will ensure that code delivered for testing has been checked to avoid many common faults.

In the default setup compilers are usually only addressing the most obvious issues when compiling, but often fails to detect deeper issues in the code.

Many of the deeper issues in the code are the causes for security and stability problems within a solution, so addressing as many as possible of them is important.

There’s no thing as “It’s just a warning”. Every warning have to be evaluated and either corrected or if not possible to correct documented and listed as a known deviation. But the deviation list must be short and easy to maintain – only have deviations for cases that are considered as “impossible” to fix.

In this article the development environment Eclipse has been used.

Eclipse Built-in Checks

The following example code is used for the demonstration of Java:


Built in checks

The compiler in default settings only detects one issue at the row “double d = Sample.getPI();” where it marks that the variable d is unused. This is of course indicating that there’s either incomplete or obsolete code, but it’s not sufficient for delivery of best quality code.

The default setting is as follows in Eclipse (part list, there are many settings).


By changing all the “Ignore” statements to “Warning” aside from a few that might be irrelevant for the solution (like the lack of “Non-externalized strings” which is relevant only if you want multi-language support) then a number of problems can be found and rectified which would cause the solution to be more useful and easier to maintain.

After enabling almost all the warnings the list increases a bit on the example code:

This gives us a few good useful items to start with when cleaning up the code.

We have now scratched the surface of issues in the code and to go deeper we need better tools, and one such tool is SpotBugs.

SpotBugs


SpotBugs have a homepage at https://spotbugs.github.io/ and it can be installed into Eclipse using the following link:

https://spotbugs.github.io/eclipse/

In the example here the sensitivity of SpotBugs have been increased to a high level to spot to also include low priority issues that usually don’t cause problems. E.g. a user provided value of Pi instead of the use of the built-in constant “Math.PI”.


 

Following the sample code and an execution of SpotBugs the error list increases a bit:


By right-clicking the issue it’s possible to get more information about the bug found and the reasoning behind it. This would help the programmer to improve the code.


The explanation for this issue looks like this:

Bug: hej.Sample.booleanMethodReturnNull() has Boolean return type and returns explicit null

A method that returns either Boolean.TRUE, Boolean.FALSE or null is an accident waiting to happen. This method can be invoked as though it returned a value of type boolean, and the compiler will insert automatic unboxing of the Boolean value. If a null value is returned, this will result in a NullPointerException.

Rank: Troubling (14), confidence: Normal

Pattern: NP_BOOLEAN_RETURN_NULL

Type: NP, Category: BAD_PRACTICE (Bad practice)

 

In this case the code could actually cause the dreaded “NullPointerException” that can make a program fail. Testing might reveal the issue in case the test coverage is sufficient, but in many cases testing only tests the expected program flow, rarely the rarer fails caused by a chain of less probable events.

Finally there’s Javadoc

Also consider to enable checks for Javadoc and fix listed issues – it will improve the maintainability of the code.

By having well-written Javadoc in the code it’s possible to generate a documentation that can be browsed with a web browser.

package hej;
public class Sample {
    public static void main(String[] args) {
        if (Sample.booleanMethodReturnNull()) {
            System.out.println("True");
        }
        Sample.invalidCast();
        if (Sample.booleanMethodReturnNull()) {
            System.out.println("True");
        }
        double d = Sample.getPI();
        Sample.stringConcat(new String[]{"a","b"});
    }
    private static void invalidCast() {
        final Object doubleValue = Double.valueOf(1.0);
        final Long value = (Long) doubleValue;
        System.out.println("   - " + value);
    }
    private static Boolean booleanMethodReturnNull() {
        return null;
    }
 private static double getPI() {
  return 3.141;
 }
    private static String stringConcat(String array[]) {
        String s = "";
        for (int i = 0; i < array.length; ++i) {
            s = s + array[i];
        }
        return s;
    }
    @Override
    public boolean equals(Object obj) {
        return ((Sample)obj) == this;
    }
}

 

I see that there are issues caused by the article editor that LinkedIn offers, I'm sorry about that. I hope that at least some of the content still is usable for anyone reading.

回复

要查看或添加评论,请登录

Nils Hammar的更多文章

  • No one will ever blame you.

    No one will ever blame you.

    The following story comes from the Wikipedia page about Richard Hamming. ( https://en.

  • Some statements to consider

    Some statements to consider

    Here are a few statements that I have collected. Below are some system design statements to consider whenever designing…

  • Ett Fossilfritt Sverige

    Ett Fossilfritt Sverige

    I en artikel i DN s? h?nvisas det till att Sverige skall ha netto nollutsl?pp ?r 2045. Det ?r v?llovligt, men…

  • Python is to 2020 what interpreting Basic was to 1985

    Python is to 2020 what interpreting Basic was to 1985

    This article is bound to upset some Python fans and those that trust external sources. Both Python and Basic shares…

    2 条评论
  • The evolution of Java

    The evolution of Java

    Even though Java is becoming a bit less popular these days due to various reasons it's still relevant. I have made a…

  • System Design Considerations

    System Design Considerations

    During my years I have accumulated some experience regarding what's good and bad in the world of designing systems…

  • Machine shop skills are getting rare

    Machine shop skills are getting rare

    The ability to work a machine shop is a great skill to have even in these days. Skilled machinists seems to be a rare…

  • Cobol - an obsolete language?

    Cobol - an obsolete language?

    The jokes about Cobol aside - it seems like there's a shortage of people that knows Cobol. On YouTube there's a "crash…

    3 条评论
  • Official COVID-19 hackathon in Sweden

    Official COVID-19 hackathon in Sweden

    An initiative by The Swedish Government. The new COVID-19 virus is testing our country, our society and us as citizens.

  • From New York Gov. Andrew Cuomo Briefing

    From New York Gov. Andrew Cuomo Briefing

    Some things to think about. Better be safe than sorry and see someone drowning in their own fluids.

社区洞察

其他会员也浏览了