Code Monkey home page Code Monkey logo

sevntu.checkstyle's People

Contributors

alex-zuy avatar alexkravin avatar aulianenko avatar baratali avatar cypai avatar damianszczepanik avatar daniilyar avatar dependabot[bot] avatar github-actions[bot] avatar hidoyatov avatar igieon avatar isopov avatar jsoref avatar maxvetrenko avatar mkordas avatar nrmancuso avatar oyarzun avatar pzygielo avatar raghavgautam avatar rdiachenko avatar rnveach avatar romani avatar sentinels23 avatar stoyank7 avatar svvladimir avatar vadimpanasiuk avatar vchekrii avatar vladlis avatar vorburger avatar yaziza avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sevntu.checkstyle's Issues

NPE in ForbidAnnotationCheck when full annotation name is used

Trying to parse the following java class ForbidAnnotationCheck will fail with NPE:

import java.awt.Component;

@org.springframework.stereotype.Component
public class ForbidAnnotationInput2 extends Component {
private static final long serialVersionUID = 1L;

}

Workaround:

import org.springframework.stereotype.Component;

@component
public class ForbidAnnotationInput2 extends java.awt.Component {
private static final long serialVersionUID = 1L;

}

New Check: NullCheckStyleInCondition

(in progress by Sergey Burtsev) check to standardize condition expressions. Safe (in C++ approach) IF conditions. Example : "if (varialble == null)" ==> "if (null == varialble)"
In Java there is no posibility to make ocasionally "=" instead of "==". so We need to force developers to write "if (varialble == null)".

http://sourceforge.net/tracker/?func=detail&aid=3004587&group_id=29721&atid=397081
https://sourceforge.net/tracker/?func=detail&aid=3103881&group_id=29721&atid=397081

New Check: ProducerExtendsConsumerSuper

ProducerExtendsConsumerSuper.
Joshua Bloch "Effective java (2nd edition)" Item 28 page 138:
"
always use Comparable<? super T> in preference
to Comparable<T>. The same is true of comparators, so you should always
use Comparator<? super T> in preference to Comparator<T>.
"
as options:

  • List of class names that are always producers. Default values for "Comparator|Comparable".
  • list of class names that are always customers.

http://sourceforge.net/p/checkstyle/feature-requests/581/

EPP: Depend on last release versions of deps

  1. Current dependency for Checkstyle is 5.4-SNAPSHOT - change it to 5.3
  2. Provide Howto on wiki for building test-jar for it, including verbose checkouting and changing branch to 5.3 release
  3. Current dependency for eclipse-cs is 5.3-SNAPSHOT - change it to 5.3
  4. Provide Howto on wiki for bulding it, including verbose checkouting and changing branch to 5.3 release

New Check: ForbidWildcardAsReturnType

ForbidWildcardAsReturnType.

Joshua Bloch, "Effective Java (2nd edition)" Item 28: page 137 :
"Do not use wildcard types as return
types. Rather than providing additional flexibility for your users, it would force
them to use wildcard types in client code.
Properly used, wildcard types are nearly invisible to users of a class. They
cause methods to accept the parameters they should accept and reject those they
should reject. If the user of a class has to think about wildcard types, there is
probably something wrong with the class’s API."

Options:

  • check public method (boolean) (default value = true)
  • check protected method (boolean) (default value = true)
  • check protected-package methods (boolean) (default value = true)
  • check private methods (boolean) (default value = false)
  • allow Wildcard with "super" (boolean). example: "? super T" (default value = false)
  • allow Wildcard with "extends" (boolean). example: "? extends T" (default value = false)
  • ignore list for Class names (regexp), example "Comparable<? super T>". (default value = "Comparable|Comparator")

http://sourceforge.net/p/checkstyle/feature-requests/580/

New Check: NeverIgnoreInteruptedException

http://today.java.net/article/2006/04/04/exception-handling-antipatterns#ignoringInterruptedException

just catch ignoring of exception by regexp pattern for Exception name. Default value is "InterruptedException" .
In Russian : http://habrahabr.ru/post/164487/ and first comment.

It might be reasonable to create general check NeverIgnoreException and by default setup it for InterruptedException. To allow developer to write any code in catch, and we can not check whether it is correct code or not - it all up to developer.

Investigate twitter custom checks and the way they are used

Here you may found instructions about custom twitter checkstyle checks:
https://github.com/twitter/commons/tree/master/build-support/checkstyle

Investigate:

  1. Since they are open sourced under Apache2 license should we somehow use them? Maybe depend on them (they are packaged as separate ivy-module, that is essentially a maven module and deployed here - http://maven.twttr.com/com/twitter/common/checkstyle/) and provide xmls for easy use of them from the eclipse-cs plugin?
  2. Their way of adding them to the checkstyle during checking the source. It seems that they are used simply adding jars with them to the classpath during checkstyle run. It seems that they use it very easily in their checkstyle ant task. If so it should be possible to use our checks in checkstyle ant task two. Provide the tutorial, how to use them with the manually downloaded sevntu-checks.jar (from the soon to be published our maven repository) and how to use them with the help of ivy.

New Check: EitherLogOrThrowCheck

There is anti-pattern - http://today.java.net/article/2006/04/04/exception-handling-antipatterns#logAndThrow

so we need to detect logging and re-throwing exception:

catch (NoSuchMethodException e) {
  LOG.error("Blah", e);
  throw e;
}

but we need to have an option to ignore cases that do logging but without exception information, so it possible that before throw we would like to print a lot of useful internal information for investigation

catch (NoSuchMethodException e) {
  LOG.error("Some information that is known only at this scope", someField);
  throw e;
}

New Check: SimpleAccesorNameNotationCheck

SimpleAccesorNameNotationCheck - check only direct fields and setter and getter. Options: 1) member prefix "m_" 2) check only simple getter/setter XXXType getXXXName(); void setXXXName(XXXType)

Partial implementation (does not work as expected): https://github.com/sevntu-checkstyle/sevntu.checkstyle/blob/master/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/SimpleAccesorNameNotationCheck.java

https://sourceforge.net/tracker/?func=detail&aid=3298879&group_id=29721&atid=397081

Check Style Ignore List

Add opportunity to checkstyle or to Eclipse Checkstyle Plug-in add to Ignore List packages and classes by some pattern or by name.

New Check: CheckFinalizeImplementation

  • Correct finalize() declaration. It is not a very simple and straight forward check, need investigation.

rules are here:
http://www.ibm.com/developerworks/ru/library/j-jtp06294/#2.3

we could check all except for calling finalize from user code (3rd in list of validations).

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() } }

AbbreviationAsWordInName problem with constants in interfaces

AbbreviationAsWordInNameChecks should ignore constants declaration in interfaces if
ignoreFinal or ignoreStatic is TRUE. As all the variables in an interface are implicitly static finals.

public interface IWorkbenchComponent  extends IPerspective {

    String TITLE = "title"; //Unexpected WARNING HERE !!!

    void dispose();
}

New Check: ConfusingConditionCheck

from PMD http://pmd.sourceforge.net/pmd-5.0.0/rules/index.html:
ConfusingTernary: Avoid negation within an "if" expression with an "else" clause. For example, rephrase: if (x != y) diff(); else same();as: if (x == y) same(); else diff();Most "if (x != y)" cases without an "else" are often return cases, so consistent use of this rule makes the code easier to read. Also, this resolves trivial ordering problems, suchas "does the error case go first?" or "does the common case go first?".

we just give idea from PMD, we have the constant problem in code - so we need to automate it a bit at least as in PMD.
We need to check even short form of conditions "?(a != b)c=1:c=2;"

OverridableMethodInConstructorCheck: problem with similar method names

Bug in public methods in c-tor.
https://github.com/romani/sevntu.checkstyle/blob/master/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/OverridableMethodInConstructorCheck.java

public ULCWorkbenchPartSite(Object input) {
    super(window, part, descriptor);
    globalActions = new ActionsHelper(part);

    init(); // warning here is corrects
    initPart(part, input); // warning here is not correct 
}
   public init() {
   ///....
   }
   private initPart() {
   ///....
   }

one case is valid another is not:
init();
initPart(part, input); // no warning should be here

Look like you have problem with name recognition as you treat them as the same methods.

New Check: ValueOfInsteadOfNewInstanceCheck

New Check to verify declaration order in Class

Check order of declaration for class(main or internal):
fields,
Annotated fields,
c-tor,
abstract methods,
Annotated methods(Autowired, Override,...),
methods,
internal classes.

As sub task:
Check nested/internal classes to be declared at the bottom of the class (after all methods/fields declaration).

Update for CustomDeclarationOrder

  1. group Fields with assigning to Anonymous classes;
private successListener = new Listener {
...
// some anonymous class definition, could be few methods definition
....
}
private int value;
private successListener2 = new new Listener {
...
// some anonymous class definition, could be few methods definition
....
}

proposed name for macros ###filed_ann_class###

  1. Setter/Geter (base on bean notation) , notation detection could be taken from https://github.com/sevntu-checkstyle/sevntu.checkstyle/blob/master/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/SimpleAccessorNameNotationCheck.java
    Marcos: ###getter_setter###
    expected order of declarations - all get/set are grouped and not mixed with other methods of class.
public int getX(){}
public int setX(){}
public int getY(){}
public int setY(){}
  1. include coverage of nested interfaces, nested enumarations
    old :" Options that are "true" by default ignoreInnerInterfaces ignoreInnerEnums"
    new create new macros: InnerInterfaces InnerEnums to help manage it location.
public class MyClass {

    interface CrazyInterface{ .... }
        ....
    }

    enum HiddenEnum{ .... }
        ....
    }
}

  1. include coverage nested classes in methods
    Options that are "true" by default
    ignoreIneerClassesInMethods

Example of bad code:

private methodX (... ) {

class NameC{ .... }
....
}

}// end of methods declaration
  1. Add support for escape symbol "" in regexp (it is required to have in regexp string usage of "(" and ")" symbols - for example describe in format location of "main()" method)
    example of usage in: "........main()...."
    Attention: see Baratali explanation for this feature.

ATTENTION: example of custom order declration format is here https://groups.google.com/d/msg/sevntu-checkstyle/_nOVtWDxPJo/sBb8s2D4lTwJ

problem with 'Avoid Hiding Cause of the Exception': if exception passed as not last parameter to c-tor

Code:

@OverRide
public Object convertToObject(String newString, Object previousValue)
throws DataTypeConversionException {
if (BigDecimal.class.equals(type)) { // fix for #279
DecimalFormat format = (DecimalFormat) NumberFormat.getNumberInstance(getLocale());
format.setParseBigDecimal(true);
try {
return format.parse(newString);
} catch (ParseException e) {
ErrorObject errorCode = new ErrorObject(ErrorCodes.ERROR_CODE_BAD_FORMAT, newString);
throw new DataTypeConversionException("Could not be converted to BigDecimal", e, errorCode); //// INCORRECT WARNING HERE!!
}
}
return convertType(super.convertToObject(newString, previousValue));
}

Please update Uts as support this case.

New Check: NoNullForCollectionReturnCheck

if return result for the method is Collection or array, show warning when it is trying to return null instead of empty collection or empty array.

Returning Null is error prone as developers forget to review method implementation or Java doc for nuances of Null meaning.

New Check: Nested Ternary

We need a check that forbids nested ternary operators. Example:

int smth = (a == b) ? -1 : (c == d) ? 0 : 1; 

This is really a bad practice.. This line should be refactored to:

int k;
if (a == b) {
    k = -1;
} else {
    if (c == d) {
    k = 0;
    }
    else {
        k = 1;
    }
}

Check should have a single option named 'ignore final' which allows to ignore statements such as:

final int smth = (a == b) ? -1 : (c == d) ? 0 : 1; 

in ctors, because in c-tors there is only one way to deal with such kind of logical operations on final variable.

Move sources to folder

Sources except eclipse-plugin-plugin reside just in root of the repository. Since we now have two connected projects - eclipse-plugin-plugin and a fork of checkstyle changes from which we are trying to put upstream, we need to mode this second project in some folder in the root of the repo.
The investigation how it can be done with git is needed.

New check: PreferMapEntryToIterateWholeMap

Consider user Map.Entry for whole map iteration instead of
getKeys() and then get value by key.
check could simply check while/for for such case. This check will not find all
weird cases but will help significantly with major cases, that are done as C++ habit, refactoring, .....

http://sourceforge.net/p/checkstyle/feature-requests/586/

from Check JavaDoc:
This check can help you to write the whole for-each map iteration more correctly:
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);
}

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);
}

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());
}

Ignore mask/options for all Checkers

It is necessary usually to switch off all validation of the CheckStyle base on:

  • @deprecated (or any other annotation)
  • File name (for example XXXXTest.java )
  • base on package name ( example: com.mycompany.badcode )

update for VariableDeclarationUsageDistanceCheck

Cases that VariableDeclarationUsageDistanceCheck have to support
1.

       int mm = Integer.parseInt(time.substring(div + 1).trim());

        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(timeNow);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        cal.set(Calendar.HOUR_OF_DAY, hh);
        cal.set(Calendar.MINUTE, mm);
        Option srcDdlFile = OptionBuilder.create("f");
        Option logDdlFile = OptionBuilder.create("o");
        Option help = OptionBuilder.create("h");

        Options options = new Options();
        options.something();
        options.addOption(srcDdlFile, logDdlFile, help);

https://sourceforge.net/tracker/index.php?func=detail&aid=3298881&group_id=29721&atid=397081#

Improve JavadocMethod Check

Improve JavadocMethod check to cover only abstract methods, or only inheritable methods, or only final methods etc.

http://sourceforge.net/tracker/index.php?func=detail&aid=2959656&group_id=29721&atid=397081

Additional request is to - Force users to write java doc for Interfaces/Abstract classes only.
http://sourceforge.net/tracker/?func=detail&aid=2959656&group_id=29721&atid=397081
http://stackoverflow.com/questions/13271326/checkstyle-check-only-method-in-interface


UPDATE: Checkstyle supports
https://checkstyle.org/config_filters.html#SuppressionXpathSingleFilter from 8.18
by means of fancy xpath expression we can exclude all not required violations while Check can not support it more easy way.

New Check: NameConvensionForTests

Force Tests to follow naming convention.
Ground: maven do not run tests that are not following naming convention (http://stackoverflow.com/questions/6178583/maven-does-not-find-junit-tests-to-run).
Requirement: Force classes having unit tests to follow naming convention - class should be named "Test_", "_Test", "_TestCase" or "_IT" (the latter is for integration tests)
Criteria: Class is considered to have tests if it has methods annotated with "@test" or it extends other class that follows naming convention.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.