Skip to content

Instantly share code, notes, and snippets.

@blundell
Created January 25, 2014 15:12
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blundell/8617812 to your computer and use it in GitHub Desktop.
Save blundell/8617812 to your computer and use it in GitHub Desktop.
Anti-Hungarian CheckStyle check
import com.puppycrawl.tools.checkstyle.api.*;
public class AntiHungarianCheck extends Check {
private static final String CATCH_MSG = "Hungarian notation belongs in the 90's. " +
"Don't prefix member variables with 'm'. " +
"Use your IDE's shiny colors. Culprit was: ";
private final HungarianNotationMemberDetector detector = new HungarianNotationMemberDetector();
@Override
public int[] getDefaultTokens() {
return new int[] { TokenTypes.VARIABLE_DEF };
}
@Override
public void visitToken(DetailAST aAST) {
String variableName = findVariableName(aAST);
if (itsAFieldVariable(aAST) && detector.detectsNotation(variableName)) {
reportStyleError(aAST, variableName);
}
}
private String findVariableName(DetailAST aAST) {
DetailAST identifier = aAST.findFirstToken(TokenTypes.IDENT);
return identifier.toString();
}
private boolean itsAFieldVariable(DetailAST aAST) {
return aAST.getParent().getType() == TokenTypes.OBJBLOCK;
}
private void reportStyleError(DetailAST aAST, String variableName) {
log(aAST.getLineNo(), CATCH_MSG + variableName);
}
}
______
import java.util.regex.Pattern;
class HungarianNotationMemberDetector {
private final Pattern pattern = Pattern.compile("m[A-Z0-9].*");
public boolean detectsNotation(String variableName) {
return pattern.matcher(variableName).matches();
}
}
@tyvsmith
Copy link

Why not just do something like:

<module name="MemberName">
            <property name="format" value="^(?!m[A-Z][a-zA-Z0-9]*)([a-z][a-zA-Z0-9]*)$"/>
            <property name="applyToPublic" value="false"/>
            <property name="applyToProtected" value="false"/>
            <property name="applyToPackage" value="false"/>
            <message key="name.invalidPattern" value="Member ''{0}'' should be named with CamelCase and without prefixes."/>
        </module>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment