Showing posts with label sevntu.checkstyle. Show all posts
Showing posts with label sevntu.checkstyle. Show all posts

Saturday, May 16, 2015

Sevntu Checkstyle release 1.13.0

Braking backward compatibility:
VariableDeclarationUsageDistanceCheck was moved to Checkstyle library . Author: Roman Ivanov
AbbreviationAsWordInNameCheck is transfered to Checkstyle library . Author: Roman Ivanov
 
 
New:
New Check RequiredParameterForAnnotationCheck. Fixes #321 . Author: Andrew Uljanenko
New Check UselessSuperCtorCallCheck implemeted. Fixes #186 . Author: Alexey
New Check EmptyPublicCtorInClassCheck implemented. fixes #291 . Author: Alexey
New Check NameConventionForJunit4TestClassesCheck implemented. Fixes #80 . Author: Alexey
New Check UselessSingleCatchCheck implemented. issue #267 fixed . Author: Alexey
New Check: AvoidConditionInversion . #112 . Author: alexkravin
New Check: NestedSwitchCheck - Checking if there is no switch block inside other switch block.  Issue #249. Author: Damian Szczepanik
 
Bugs:
fix for NPE in ConfusingConditionCheck . Author: melodicwing
Fixed false positive in check ForbidReturnInFinallyBlockChech. Fixes #269 . Author: Andrew Uljanenko
Diamond operator - fixed violations on anonymous classes . Issue #270 . Author: alexkravin
 
 
Miscellaneous:
Refactored prefixes, changed indentation of switch-case, issue #298 . Author: alexkravin
Moved test-input folder from src/test/java to src/test/resources . Author: alexkravin
no java6 support since 6.2 release . Author: Roman Ivanov
version 1.13.0 bump, java6, fixes for errors of m2e . Author: Roman Ivanov
Updated maximum line length to 100 symbols . Author: Daniil Yaroslavtsev
Small code changes and extended UT's. Fixes #317 . Author: Andrew Uljanenko
New test case added. Fixes #275 . Author: Andrew Uljanenko
New test case added. Fixes #274 . Author: Andrew Uljanenko
Extended javadoc, UTs. Fixed #264 . Author: Andrew Uljanenko
 
Code coverage improvement . Author: Damian Szczepanik
Short-circuit logic is used in boolean expressions, issue #169 . Author: Michal Kordas
Code coverage improvements for ReturnCountExtendedCheck . Author: Damian Szczepanik
Improved AvoidHidingCauseExceptionCheck code coverage . Author: Damian Szczepanik
Improved UselessSingleCatchCheck code coverage . Author: Damian Szczepanik
Improved AvoidDefaultSerializableInInnerClasses code coverage to 100% . Author: Damian Szczepanik
Fixes several Sonar violations . Author: Damian Szczepanik
Remove unused input for AvoidHidingCauseExceptionCheck . Author: Damian Szczepanik
Increase AvoidNotShortCircuitOperatorsForBooleanCheck code coverage Pull #324 . Author: Damian Szczepanik
Moved static duplicated methods into Utils class . Author: Damian Szczepanik
Sonar violation: Tabulation characters should not be used . Author: Damian Szczepanik
improved InterfaceTypeParameterNameCheck code coverage . Author: Damian Szczepanik
Improved UnnecessaryParenthesesExtendedCheck test coverage . Author: Damian Szczepanik
Fixed Sonar critical and major violations: - "static final" arrays should be "private" - "for" loop incrementers should modify the variable being tested in the loop's stop condition - Declarations should use Java collection interfaces such as "List" rather than specific implementation classes such as "LinkedList" . Author: Damian Szczepanik
Run cobentura with mvn check or mavn install and fail if code coverage criteria are not met. For new files we expect to have 100% code coverage, for older one that do not pass this rule we added some rules . Author: Damian Szczepanik
Added Utils class that has one method for reporting unsupported AST token . Author: Damian Szczepanik
Removed duplicate check for the empty list: first condition isEmpty() but then for-each which also skips iteration if list is empty . Author: Damian Szczepanik
Increase OverridableMethodInConstructorCheck code coverage: - Added more test cases (examples) - Replaced to Serializable/Clonable stirngs to Cloneable.class.getSimpleName() - Increase coverage by using true and false values of checkCloneMethod and checkReadObjectMethod . Author: Damian Szczepanik
MapIterationInForEachLoopCheck - Converted strings to .class.getName() - moved initialization to beginTree method . Author: Damian Szczepanik
Improved test coverity of EitherLogOrThrowCheck by: - adding new test with inner class - invoking setters method by setting attributes in test scenario . Author: Damian Szczepanik
Improved test coverity in ConfusingConditionCheck by setting default parameters in test case . Author: Damian Szczepanik
Improved coverage of AvoidDefaultSerializableInInnerClasses by importing full qualified class name Serializable (use java.io.Serializable) . Author: Damian Szczepanik
Improved test coverity of class ChildBlockLengthCheckCheck by adding test for tested class . Author: Damian Szczepanik
Improved CustomDeclarationOrderCheck - Added tests to increase coverage - Fixed rule in test method - Fixed formatting (indents) . Author: Damian Szczepanik

Tuesday, October 14, 2014

Sevntu Checkstyle release 1.12.0

new release of Checkstyle extension (Sevntu.Checkstyle) 1.12.0, with new checks:
DiamondOperatorForVariableDefinitionCheck,
PublicReferenceToPrivateTypeCheck,
TernaryPerExpressionCountCheck

Updates in:
RedundantReturnCheck
CustomDeclarationOrderCheck
LineLengthCheck
ForbidThrowAnonymousExceptionsCheck,

Details:
http://daniilyar.blogspot.com/2014/10/sevntu-checkstyle-release-112-checks.html

Thursday, May 8, 2014

Sevntu Checkstyle release 1.11.0


official page: http://sevntu-checkstyle.github.io/sevntu.checkstyle/#1.11.0


 New and noteworthy:

1) new Check "Enum Values Check", issue, done by Pavel Baranchikov.

Check forces enum values to match the specific pattern. According to "Java Coding Style" by Achut Reddy p 3.3 constants include "all static final object reference types that are never followed by " ." (dot).", i.e. enums, which are followed by dot while used in the code are to be treated as static object references, while enums, that are not used with following dot, should be treated as constants.
Enums are defined to be used as class have some own methods. This condition is used to distinguish between Values Enumeration and Class Enumeration. Values Enumeration looks like the following:
enum SimpleErrorEnum
  {
      FIRST_SIMPLE, SECOND_SIMPLE, THIRD_SIMPLE;
  }
While Class Enumeration has some methods, for example:
 enum SimpleErrorEnum
   {
       FIRST_SIMPLE, SECOND_SIMPLE, THIRD_SIMPLE;
 
       public String toString() {
           return Integer.toString(ordinal() + 10);
       }
   }
Name format for Class Enumeration is specified with setObjFormat(String) , while format for enum constants - with setConstFormat(String)
To avoid assuming enum as static object reference, while using some specific methods, setExcludes(List) can be used. For example to make enum in the previous example a constant set Excludes property to a value toString
By default toString is used as an exclusion.

2) new Check "Map Iteration In For Loop", issue, done by Max Vetrenko

This check can help you to write the whole for-each map iteration more correctly:
  1. If you iterate over a map using map.keySet() or map.entrySet(), but your code uses only map values, Check will propose you to use map.values() instead of map.keySet() or map.entrySet(). Replacing map.keySet() or map.entrySet() with map.values() for such cases can a bit improve an iteration performance.Bad:
    for (Map.Entry; entry : map.entrySet()){
       System.out.println(entry.getValue());
    }
    for (String key : map.keySet(){
       System.out.println(map.get(key));
    }
    Good:
    for (String value : map.values()){
       System.out.println(value);
    }
  2. If you iterate over a map using map.entrySet(), but never call entry.getValue(), Check will propose you to use map.keySet() instead of map.entrySet(). to iterate over map keys only.Bad:
    for (Map.Entry entry : map.entrySet()){
       System.out.println(entry.getKey());
    }
    Good:
    for (String key : map.keySet()){
       System.out.println(key);
    }
  3. If you iterate over a map with map.keySet() and use both keys and values, check will propose you to use map.entrySet() to improve an iteration performance by avoiding search operations inside a map. For this case, iteration can significantly grow up a performance.Bad:
    for (String key : map.keySet()){
       System.out.println(key + "  " + map.get(key));
    }
    Good:
    for (Map.Entry entry : map.entrySet()){
       System.out.println(entry.getValue() + "   " + entry.getKey());
    }


3) new check "Forbid Throw Anonymous Exception", issue, done by Max Vetrenko.

Forbid throwing anonymous exception. limitation: This Check does not validate cases then Exception object is created before it is thrown.
For example:
catch (Exception e) {
   throw new RuntimeException() { //anonymous exception
    //some code
   };


4) new check "Finalize Implementation", issue, done by Max Vetrenko.

This Check detects 3 most common cases of incorrect finalize() method implementation:
  • negates effect of superclass finalize
    protected void finalize() { }
    protected void finalize() { doSomething(); }
  • useless (or worse) finalize
    protected void finalize() { super.finalize(); }
  • public finalize
    public void finalize() {
       try { doSomething(); } 
       finally { super.finalize(); } 
    }
    


5) Update for CustomDeclarationOrderCheck, issue, done by Baratali Izmailov.

details, In short:
1) macros for Fields with assigning to Anonymous classes
2) macros for Setter/Geter
3) macros for nested interfaces, nested enumarations
4) Inner Classes in methods are ignored
5) macros for "main()" method

Format with usage of all marcoses could be found there.

General information:
repository: https://github.com/sevntu-checkstyle/sevntu.checkstyle
mail-list: https://groups.google.com/forum/?hl=en#!forum/sevntu-checkstyle

Sunday, January 19, 2014

Checkstyle: ULC classes as static variables

Example of AvoidModifiersForTypesCheck in real code validation, implemented in sevntu.checkstyle 1.0.5 .

http://ulc.canoo.com/ulccommunity/Contributions/Extensions/GoodPractices.html

Static variables
Never keep instances of ULC classes in static variables (ULCIcons neither!). They cannot be shared between different sessions.

Post on ULC Canoo site that helps, at forum .

Saturday, January 11, 2014

Confusing Condition Check examples

Our team implemented very impudent Check - ConfusingConditionCheck in release 1.9.0.

In short, This check prevents negation within an "if" expression if "else" is present.
For example, rephrase:
if (x != y) smth1(); else smth2();
as:
if (x == y) smth2(); else smth1();

But we are not that simple !!! in other case Check will not be useful in real live so we have bunch of options...

Options:

multiplyFactorForElseBlock - Allow to ignore "else" block if its length is in
 "multiplyFactorForElseBlocks" time less then "if" block.

ignoreInnerIf - Disable warnings for all "if" that follows the "else". It is useful for
 save similarity with all "if-then-else" statement.

ignoreSequentionalIf - Disable warnings for all sequential "if". warnings for all "if" that follows the "else".

ignoreNullCaseInIf - Disable warnings for "if" if it condition contains "null".

ignoreThrowInElse - Disable warnings for "if" if "else" block contain "throw".


Examples for each option.

our UTs input file is here.

1) Example of Simple IF-ELSE with inversion
that could be swapped in their position and condition could be inverted
String[] result = null;
if (!checkNotExists) {   /// warning is here !!!!
  result = new String[] { updateSql };
} else {
  result = new String[] { updateSql, removeItems(table, column) };
}

another example:
if (!popup.isShowing()) {  /// warning is here !!!!
  show();
} else {
  hide();
}

 another example with complicated condition:
if (!global && part != this) {  // warning is here !!!
  addLocalPart(part);
} else {
  addGlobalInternal(part);
}
code is expected to be, base on De Morgan's laws from Boolean Algebra:
if (global || part == this) { 
  addGlobalInternal(part);
} else {
  addLocalPart(part);
}


2) Example of multiplyFactorForElseBlock=4 .
IF condition is negative but as it big enough(mean that is could be more valuable for developer attention) it should stay in on top so that option skip that case.
  if (!hasWhitespaces(kw)) { //NO warning here   sb.append(kw);
  sb.append('"');
  sb.append('--"');
  sb.append('"');
sb.append('--"'); } else { sb.append(kw); } 
3) example with ignoreNullCaseInIf=true.
Check for NULL is used everywhere in code, and developer by that check highlight that first block is main logic, ELSE block is exceptional processing, so we keep condition without inversion as IF block is more valuable for logic.
if (entity != null) { //NO warning here handler.handleReference(entity); } else { log.error("Some problems with resolving reference"); }

4) Example with ignoreSequentionalIf = true; 
Such pattern is also well spread in java code, unfortunately there it hard to say that after inverting logic IF-ELSE will looks better.
if (!isAllowed(row)) {   //NO warning here
label.setForeground(Color.gray);
} else if (isSelected) {
label.setForeground(Color.white);
} else {
label.setForeground(Color.black);
}
there is even more complicated, so it is user responsibility what conditions should be used and what processing block should located above:
if (obj1 == obj2) {
result = true;
} else if (obj1.getClass() != obj2.getClass()) {   //NO warning here
result = false;
} else {
Class<?> obj1Class = obj1.getClass();
     // a lot of code .......
   }
to see more examples please visit issue at github.

5) Example for ignoreThrowInElse=true;
ELSE block is always treated as processing of non main part of logic, so all unexpected processing and terminations are expected in it more than in IF.
By mean of this option you can skip cases where ESLE is used to process exceptional cases of logic, so main block of logic have to be placed on top.

if (!gzip) {  //NO warning here due to "throw" in ESLE
  stream = new BufferedInputStream(in);
} else {
  log.debug("resource is gzip'd: " + url);
try {
  stream = new BufferedInputStream(new GZIPInputStream(in));
} catch (IOException e) {
  throw new DocumentException(e);
}
}

6) Example of ingnoreInnerIf = true
With that option as "true" this Check will not force you to update following code

if (user != null ) {
   if (obj !=  null ) {
         index++;
   }
} else { 
     index--; 
}

to

if (user == null ) {
    index--;
} else {     
   if (obj !=  null ) {
           index++;
   }
 }

It is some time convenient to keep the same type conditions "!=" close together(close to each other). But it is very debatable what variant is more readable - so it is option :) .

Thursday, November 28, 2013

Sevntu Checkstyle release 1.10.0

official page: http://sevntu-checkstyle.github.io/sevntu.checkstyle/#1.10.0

New and noteworthy:

New project! sevntu-checkstyle-sonar-plugin -  Project was created as extension to Sonar Checkstyle Plugin for SonarQube, How to use it is described here in detail and pictures, Done by Ruslan Diachenko. More.

New project! sevntu-checkstyle-idea-extension -  Project was created as extension for Checkstyle IDEA plugin for IntelliJ IDEA, How to use it  is described here in details and pictures, Done by Vadim Panasiuk. More.

Bug fixing and improvements in existing Checks: 

CustomDeclarationOrderCheck -  Inner Classes in methods are ignored. Done by Baratali Izmailov. More.

VariableDeclarationUsageDistanceCheck -  Update to ignore raising violation against block constructions/builders and methods with long list arguments, Done by Baratali Izmailov. More.

ConfusingConditionCheck -  Update to skip raising violations on sequential IF, Done by Vadim Panasiuk. More.

NoNullForCollectionReturnCheck -  Fix for NulPointerException, Done by Ilja Dubinin. More.

ForbidCertainImportsCheck -  additional field as Regexp for specifying ignored imports from forbidden, Done by Daniil Yaroslavtsev. More.

Updates in messages -  Done by Baratali Izmailov, Ilja Dubinin, Vadim Panasiuk. More.



General information:
repository: https://github.com/sevntu-checkstyle/sevntu.checkstyle
mail-list: https://groups.google.com/forum/?hl=en#!forum/sevntu-checkstyle

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 ...... .