Dataflow anomaly analysis warnings from PMD

前端 未结 2 690
攒了一身酷
攒了一身酷 2020-12-17 09:21

I am using Eclipse with the PMD Plug-in (4.0.0.v20130510-1000) and get a lot of those violations:

Found \'DD\'-anomaly for variable \'freq\' (line

相关标签:
2条回答
  • 2020-12-17 09:58
    double freq; // (1)
    try {
      // here I get a DU anomaly
      freq = Double.parseDouble(getFrequencyTextField().getText());
    } catch (final NumberFormatException e) {
      Log.e(e.getMessage());
      freq = 0; // (2)
    }
    if (freq < 10E6) doSomething();
    

    The first problem is that in the catch the parseDouble assignment is not done to freq. On an exception freq still would be 0. Maybe flaggable. So it goes away when assigning to freq inside catch.

    When assigning to freq in the catch, (2), the inital assignment, (1), would never be read, so only a declaration suffices.

    With respect to better style:

    try {
      // here I get a DU anomaly
      double freq = Double.parseDouble(getFrequencyTextField().getText());
    
      if (freq < 10E6) doSomething();
      ...
    
    } catch (final NumberFormatException e) {
      Log.e(e.getMessage());
    }
    

    Or follow the answer of @JoachimSauer, using a double conversion that does not throw an exception. The logging would indicate a level of seriousness in preference of the above style. Logging inside a simple conversion function on error might not be good style: too much logging, ignored logging (?), hard to repair.

    0 讨论(0)
  • 2020-12-17 10:10

    You could get around this problem (and separate concerns a bit more clearly) by extracting the parsing into a separate method:

    double freq = parseDouble(getFrequencyTextField().getText());
    
    // later in the class (or in a utility class):
    
    public static double parseDouble(final String input) {
      try {
        return Double.parseDouble(input);
      } catch (final NumberFormatException e) {
        Log.e(e.getMessage());
        return 0;
      }
    }
    

    And if you have different default values, you could also add a two-argument version: public static double parseDouble(final String input, final double defaultValue).

    0 讨论(0)
提交回复
热议问题