Showing posts with label check. Show all posts
Showing posts with label check. Show all posts

Tuesday, March 10, 2015

Static Import Check for Checkstyle

Static import: http://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html

Command to catch code:
 grep --include=*.java --exclude={*Test.java,Test*.java,*IT.java} -rw -m 1 . -e "import static"

we can not forbid static import usage at all, it is useful, we need to limit it, So we will forbid all static imports that are not applying to following options:

1) allow in target member is used more then X times.
see example in point "3)" and imagine there is a lot of such code blocks, that option could allow static import for "psvBuilder".

2) allow in Class of target member could brake Line-limit more then X times.
 that it is not required as will hide too much code that should be formatted appropriately

3) Allow in complicated statements with a lot of inner methods calls in arguments.

import static com.commons.domain.DsvFileDefinition.psvBuilder;
import static com.commons.domain.FeedDefinition.feedBuilder;
import static com.commons.domain.ZipFileDefinition.zipBuilder;

private static FeedDefinition getFeedDefinition() {
return feedBuilder("Premium", "/datafeeds/", "NAME", "NAME1").addFile(
zipBuilder("premium").addFiles(of(
psvBuilder("address").build(),
psvBuilder("entity").build(),public enum BetPosition {
    // ...
    STRAIGHT_32(96, ...),
    STRAIGHT_33(142, ...),
    STRAIGHT_34(52, ...),
    BET_1_2(53, ...),
    BET_4_5(55, ...),
    // ... long list of enum values

psvBuilder("entity_changes").build(),
psvBuilder("entity_identifiers").build(),
psvBuilder("entity_names").build(),
psvBuilder("entity_profiles").build(),
psvBuilder("entity_relationships").build(),
psvBuilder("entity_structure").build(),
psvBuilder("entity_map").build(),
psvBuilder("listing_map").build())).build()
).build();


4) Ignore list of classes/methods that team presume distinctive and whole team know.
"com.google.common.base.Strings,com.google.common.base.XXXXXXX"

import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.base.Strings.nullToEmpty;

this.schemaName = nullToEmpty(schemaName);
if (isNullOrEmpty(tableName)) {
throw new IllegalArgumentException("tableName could not be empty");
}
this.tableName = tableName;

5)
Invalid usage:
import static com.google.common.collect.Iterables.getFirst;
....

TreeSet<Name> names = Sets.newTreeSet(new ILifeCycleEntityComparator());
if (names.isEmpty()) {
// do smth 
} else {
Name firstName = getFirst(tradenames, null);public enum BetPosition {
    // ...
    STRAIGHT_32(96, ...),
    STRAIGHT_33(142, ...),
    STRAIGHT_34(52, ...),
    BET_1_2(53, ...),
    BET_4_5(55, ...),
    // ... long list of enum values

// do smth else
}

6)
Here looks like static import allow to keep lines short.

import static com.revere.det.core.domain.validation.ValidationUtils.formatPeriod;

details.append("Focused sector: ").append(focusSector.getPath())
.append(", start date of focus: ").append(formatPeriod(focus.getStartDate()))
.append(", end date of focus: ").append(formatPeriod(focus.getEndDate()))
.append(NEW_LINE);

7)
Inappropriate - used only one time in whole file.

import static org.joda.time.LocalDateTime.now;

public class Builder extends DataBuilder {

private static final java.sql.Date THREE_YEARS_AGO = new java.sql.Date(now().minusYears(3).toDate().getTime());

=======================

https://code.google.com/p/guava-libraries/wiki/FunctionalExplained

Even using static imports, even if the Function and the Predicate declarations are moved to a different file, the first implementation is less concise, less readable, and less efficient.   

=================

Here's a shortened version of a class where static import is suitable:

===============================
import static com.some.company.BetPosition.*;

public class NumberMapping {

    private final BetPosition[][] numberToPositions = new BetPosition[][] {
            /* 0 number */{ STRAIGHT_0, BET_0_1, BET_0_2, BET_0_3, BET_0_1_2, BET_0_2_3, BET_0_1_2_3 },                 
            // ... 1-35 ...
            /* 36 number */{ STRAIGHT_36, BET_35_36, BET_33_36, BET_34_35_36, BET_32_33_35_36, BET_31_32_33_34_35_36,
                    TOP_2_TO_1, DOZEN_3_RD_12, HIGH_19_TO_36, RED, EVEN } };

    public BetPosition[] getPositions(int number) {
        BetPosition[] positions = numberToPositions[number];
        // some logic
        return positions;
    }
}


Where BetPosition is an enum with such a content:

public enum BetPosition {
    // ...
    STRAIGHT_32(96, ...),
    STRAIGHT_33(142, ...),
    STRAIGHT_34(52, ...),
    BET_1_2(53, ...),
    BET_4_5(55, ...),
    // ... long list of enum values

====================================

TODO..... investigate Guava code to have be sure that their code could follow that Check.

Issue is registered:
https://github.com/sevntu-checkstyle/sevntu.checkstyle/issues/453 

Monday, January 13, 2014

New Checkstyle idea: Appropriate Name Check

It is very ambition task but :) it will be good to have such Check to control typos and restrict non-English developers to write ease-to-read code.

Main focus on ensure that methods start  from verb, variable and Classes are nouns/adjectives (very difficult, separate vocabulary, ...... could be done as student diploma work).
As an option - Grammar validation for names of variables, methods, classes base on vocabulary - it will be very good experiment.

Attention for interesting Naming examples to consider for Class names and Boolean names:
http://checkstyle.sourceforge.net/availablechecks.html
AvoidStarImport - name started from verb.
allowByTrailComment - name started from verb - Boolean  variable , is there better name ?

so Check should be not that strict or rules for naming should be more complicated.

We could borrow spelling/grammar check from Eclipse.
Is there any other OSS library ?

Spell projects:
https://github.com/lyda/misspell-check



If you run to this page and share idea with me, please let me know.

Wednesday, November 6, 2013

Checkstyle idea - require toString() method for Classes

toString() is required for classes that do logging as error to print context of them-self and around.

it might be reasonable to put in toString() only simple types fields that are provided by setXXXXX().

Johua Bloh idea about toString() for classes - Effective Java 2 book - "Item 10: Always override toString" - http://jtechies.blogspot.com/2012/07/item-10-always-override-tostring.html.

Having useful toString() make logging of context during error a simple and pleasant task.

Questions: What criteria we could follow to make a Check that will not force all Classes to have toString() on domains and critical for logging?

Override toString() everywhere is not practical, so we need figure out distinctive characteristics of Classes that have to do it.
- Class that is POJO
- ....

if somebody have ideas please share them on https://groups.google.com/forum/?hl=en#!forum/sevntu-checkstyle or https://groups.google.com/forum/?hl=en#!forum/checkstyle-devel

Monday, October 28, 2013

Trailing Comment Check false positives

Original investigation of Daniil Yroslavtsev:

Check: http://checkstyle.sourceforge.net/config_misc.html#TrailingComment
It has so much problem to report valid code so I do believe that it is switched off  in all companies configurations.

Other support for that Check: Trailing Comments .

But currently Trailing Comment check warns on the following valid cases:

1.

  A. 
  } catch (Exception e) { // SUPPRESS CHECKSTYLE IllegalCatchExtendedCheck now it part of logic

  B.
  } catch (Exception e) { // NOPMD

  C.
  } catch (Exception e) { // NOSONAR

2.
double emerging = 100 - regions.sumEstimate(
  "54138", // Not Applicable/Disclosed
  "19668", // United States
  "200005", // Canada
...
);
ATTENTION: it is not false-positive, as all this magic numbers
 should be moved to constants with proper names



3.


ReportValidationResult r = validationResult.get(i);
  sb.append(
    MessageFormat.format("  report_id={0} (co_id={1}), report_start$=''{2}'', report_end$=''{3}''"
     + ", period_start_date={4}, period_end_date={5}: "
     + "total percent on ''{6}'' is {7}% .... ",
     safeToPlainString(r.reportId), // 0
     safeToPlainString(r.companyId), // 1
     formatTimestamp(r.reportStartDate), // 2
     ...
     formatTimestamp(r.periodEndDate), // 7
     ...
     )

4.

  private static final Color[] COLORS = {             
            new Color(255, 128, 128), // pink
            new Color(255, 255, 128), // yellow             
            new Color(128, 255, 128), // green             
            new Color(128, 255, 255), // cian             
            new Color(255, 128, 192), // margent                      
            new Color(255, 128, 64), // brown
            new Color(0, 128, 128), // blue/gray
            new Color(128, 128, 255), // purple
            new Color(0, 128, 0), // dark green             
            new Color(128, 128, 0), // greenish/grayish     };

5
    record[++columnIndex] = geoAreaEntry.getKey(); // _NAME
    record[++columnIndex] = "unknown"; // _REGION
    record[++columnIndex] = "0"; // _WEIGHT
    record[++columnIndex] = "1"; // _CONF



To fix false-positives we can update Trailing Commentary Sonar check to ignore: //NOSONAR, //SUPPRESS CHECKSTYLE, //NOPMD, // formatter:off, // formatter:on commentaries (with all their possible variants) and other 'valid' comments by regexp in it`s configuration.

But I think, that Checkstyle Trailing Comment check should be disabled for all projects as too many comment formats can be considered as 'valid' and result 'ignore' regexp will be too complex and unreadable.

Sunday, November 11, 2012

SevNTU Checkstyle version 1.6

We finished new version of our extension for Checkstyle - release 1.6.
I updated wiki pages to allow other developers easily join the project.
Read our publications, in Russian language, latest is for 1.5.3 release, for 1.6 will be soon.

Release 1.6.0 (21/October/2012):

LogicConditionNeedOptimizationCheck -  This check prevents the placement of local variables and fields after calling methods in '&&' and '||' conditions. Done by Ilja Dubinin.
Example:
"if (isVisible() && active)" == should be refactored to ==> "if (active && isVisible())"
Reason: swap of conditions expressions will be beneficial, but some time you can find logic that in isVisible() change 'active' variable value and this optimization will not be correct - but this is sign of bad  design!

ForbidCCommentsInMetods -  Check prevents usage of C-style (/* ... */) comments inside method body. If you have class declaration inside method body with JavaDoc you will get error too, that is sad side effect for now, but I did not met such cases for now, so I thunk it will be incentive to move class out. Done by Ilja Dubinin.
Reason: C-style of comments are problem for future investigation, it should be treated as DEBUG/temporal comments, but should be cleared finally.

InterfaceTypeParameterNameCheck -  Checks that interface type parameter(for template) names conform to a format specified by the format property. Default format is ^[A-Z]$. Done by Dmitry Gridyushko.
Reason: to avoid template types to be like <INPUT>, <CUSTOM>, <LISTENER> and force developer to name them by 1 letter <I>, <C>, <L>. to clearly indicate nature of variable in code down the file.

All details are here: http://sevntu-checkstyle.github.com/sevntu.checkstyle/
We will do bug fixing in 1.6.1 and 1.6.2 as always, please test and report bug ...... .