ConstructorCallsOverridableMethod.java

Index Score
net.sourceforge.pmd.rules
PMD

View: Reasons, Metrics, Source Code

These are the metrics that contribute to the Enerjy Score for this file, ranked by impact. So the metrics listed at the top influence the score to a greater extent that the metrics listed at the bottom.

MetricDescription
EXEC_COMMENTSComments in executable code
LINE_COMMENTNumber of line comments
SIZESize of the file in bytes
JAVA0144JAVA0144 Line exceeds maximum M characters
JAVA0049JAVA0049 Nested block at depth N (maximum: M)
BLOCKSNumber of blocks
JAVA0053JAVA0053 Unused label
JAVA0117JAVA0117 Missing javadoc: method 'method'
EXITSProcedure exits
CYCLOMATICCyclomatic complexity
JAVA0108JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
OPERATORSNumber of operators
JAVA0128JAVA0128 Public constructor in non-public class
PROGRAM_LENGTHHalstead program length
OPERANDSNumber of operands
LINESNumber of lines in the source file
LOGICAL_LINESNumber of statements
FUNCTIONSNumber of function declarations
LOCLines of code
COMMENTSComment lines
JAVA0266JAVA0266 Use of System.out
COMPARISONSNumber of comparison operators
UNIQUE_OPERANDSNumber of unique operands
DOC_COMMENTNumber of javadoc comment lines
ELOCEffective lines of code
PROGRAM_VOCABHalstead program vocabulary
LOOPSNumber of loops
JAVA0110JAVA0110 Incorrect javadoc: no @return tag
PARAMSNumber of formal parameter declarations
INTERFACE_COMPLEXITYInterface complexity
JAVA0034JAVA0034 Missing braces in if statement
JAVA0123JAVA0123 Use all three components of for loop
JAVA0254JAVA0254 Use enhanced for loop construct instead of Iterator
RETURNSNumber of return points from functions
NEST_DEPTHMaximum nesting depth
JAVA0130JAVA0130 Non-static method does not use instance fields
JAVA0007JAVA0007 Should not declare public field
JAVA0116JAVA0116 Missing javadoc: field 'field'
PROGRAM_VOLUMEHalstead program volume
JAVA0259JAVA0259 Return of collection/array field
UNIQUE_OPERATORSNumber of unique operators
JAVA0126JAVA0126 Method declares unchecked exception in throws
JAVA0043JAVA0043 Inner class does not use outer class
JAVA0113JAVA0113 Incorrect javadoc: no @author tag
JAVA0256JAVA0256 Assignment of external collection/array to field
JAVA0145JAVA0145 Tab character used in source file
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.rules; import net.sourceforge.pmd.AbstractRule; import net.sourceforge.pmd.ast.ASTArguments; import net.sourceforge.pmd.ast.ASTClassOrInterfaceDeclaration; import net.sourceforge.pmd.ast.ASTCompilationUnit; import net.sourceforge.pmd.ast.ASTConstructorDeclaration; import net.sourceforge.pmd.ast.ASTEnumDeclaration; import net.sourceforge.pmd.ast.ASTExplicitConstructorInvocation; import net.sourceforge.pmd.ast.ASTLiteral; import net.sourceforge.pmd.ast.ASTMethodDeclaration; import net.sourceforge.pmd.ast.ASTMethodDeclarator; import net.sourceforge.pmd.ast.ASTName; import net.sourceforge.pmd.ast.ASTPrimaryExpression; import net.sourceforge.pmd.ast.ASTPrimaryPrefix; import net.sourceforge.pmd.ast.ASTPrimarySuffix; import net.sourceforge.pmd.ast.AccessNode; import net.sourceforge.pmd.ast.Node; import net.sourceforge.pmd.ast.SimpleNode; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; /** * Searches through all methods and constructors called from constructors. It * marks as dangerous any call to overridable methods from non-private * constructors. It marks as dangerous any calls to dangerous private constructors * from non-private constructors. * * @author CL Gilbert (dnoyeb@users.sourceforge.net) * @todo match parameter types. Aggressively strips off any package names. Normal * compares the names as is. * @todo What about interface declarations which can have internal classes */ public final class ConstructorCallsOverridableMethod extends AbstractRule { /** * 2: method(); * ASTPrimaryPrefix * ASTName image = "method" * ASTPrimarySuffix * *ASTArguments * 3: a.method(); * ASTPrimaryPrefix -> * ASTName image = "a.method" ??? * ASTPrimarySuffix -> () * ASTArguments * 3: this.method(); * ASTPrimaryPrefix -> this image=null * ASTPrimarySuffix -> method * ASTPrimarySuffix -> () * ASTArguments * <p/> * super.method(); * ASTPrimaryPrefix -> image = "method" * ASTPrimarySuffix -> image = null * ASTArguments -> * <p/> * super.a.method(); * ASTPrimaryPrefix -> image = "a" * ASTPrimarySuffix -> image = "method" * ASTPrimarySuffix -> image = null * ASTArguments -> * <p/> * <p/> * 4: this.a.method(); * ASTPrimaryPrefix -> image = null * ASTPrimarySuffix -> image = "a" * ASTPrimarySuffix -> image = "method" * ASTPrimarySuffix -> * ASTArguments * <p/> * 4: ClassName.this.method(); * ASTPrimaryPrefix * ASTName image = "ClassName" * ASTPrimarySuffix -> this image=null * ASTPrimarySuffix -> image = "method" * ASTPrimarySuffix -> () * ASTArguments * 5: ClassName.this.a.method(); * ASTPrimaryPrefix * ASTName image = "ClassName" * ASTPrimarySuffix -> this image=null * ASTPrimarySuffix -> image="a" * ASTPrimarySuffix -> image="method" * ASTPrimarySuffix -> () * ASTArguments * 5: Package.ClassName.this.method(); * ASTPrimaryPrefix * ASTName image ="Package.ClassName" * ASTPrimarySuffix -> this image=null * ASTPrimarySuffix -> image="method" * ASTPrimarySuffix -> () * ASTArguments * 6: Package.ClassName.this.a.method(); * ASTPrimaryPrefix * ASTName image ="Package.ClassName" * ASTPrimarySuffix -> this image=null * ASTPrimarySuffix -> a * ASTPrimarySuffix -> method * ASTPrimarySuffix -> () * ASTArguments * 5: OuterClass.InnerClass.this.method(); * ASTPrimaryPrefix * ASTName image = "OuterClass.InnerClass" * ASTPrimarySuffix -> this image=null * ASTPrimarySuffix -> method * ASTPrimarySuffix -> () * ASTArguments * 6: OuterClass.InnerClass.this.a.method(); * ASTPrimaryPrefix * ASTName image = "OuterClass.InnerClass" * ASTPrimarySuffix -> this image=null * ASTPrimarySuffix -> a * ASTPrimarySuffix -> method * ASTPrimarySuffix -> () * ASTArguments * <p/> * OuterClass.InnerClass.this.a.method().method().method(); * ASTPrimaryPrefix * ASTName image = "OuterClass.InnerClass" * ASTPrimarySuffix -> this image=null * ASTPrimarySuffix -> a image='a' * ASTPrimarySuffix -> method image='method' * ASTPrimarySuffix -> () image=null * ASTArguments * ASTPrimarySuffix -> method image='method' * ASTPrimarySuffix -> () image=null * ASTArguments * ASTPrimarySuffix -> method image='method' * ASTPrimarySuffix -> () image=null * ASTArguments * <p/> * 3..n: Class.InnerClass[0].InnerClass[n].this.method(); * ASTPrimaryPrefix * ASTName image = "Class[0]..InnerClass[n]" * ASTPrimarySuffix -> image=null * ASTPrimarySuffix -> method * ASTPrimarySuffix -> () * ASTArguments * <p/> * super.aMethod(); * ASTPrimaryPrefix -> aMethod * ASTPrimarySuffix -> () * <p/> * Evaluate right to left */ private static class MethodInvocation { private String m_Name; private ASTPrimaryExpression m_Ape; private List<String> m_ReferenceNames; private List<String> m_QualifierNames; private int m_ArgumentSize; private boolean m_Super; private MethodInvocation(ASTPrimaryExpression ape, List<String> qualifierNames, List<String> referenceNames, String name, int argumentSize, boolean superCall) { m_Ape = ape; m_QualifierNames = qualifierNames; m_ReferenceNames = referenceNames; m_Name = name; m_ArgumentSize = argumentSize; m_Super = superCall; } public boolean isSuper() { return m_Super; } public String getName() { return m_Name; } public int getArgumentCount() { return m_ArgumentSize; } public List<String> getReferenceNames() { return m_ReferenceNames;//new ArrayList(variableNames); } public List<String> getQualifierNames() { return m_QualifierNames; } public ASTPrimaryExpression getASTPrimaryExpression() { return m_Ape; } public static MethodInvocation getMethod(ASTPrimaryExpression node) { MethodInvocation meth = null; int i = node.jjtGetNumChildren(); if (i > 1) {//should always be at least 2, probably can eliminate this check //start at end which is guaranteed, work backwards Node lastNode = node.jjtGetChild(i - 1); if ((lastNode.jjtGetNumChildren() == 1) && (lastNode.jjtGetChild(0) instanceof ASTArguments)) { //could be ASTExpression for instance 'a[4] = 5'; //start putting method together // System.out.println("Putting method together now"); List<String> varNames = new ArrayList<String>(); List<String> packagesAndClasses = new ArrayList<String>(); //look in JLS for better name here; String methodName = null; ASTArguments args = (ASTArguments) lastNode.jjtGetChild(0); int numOfArguments = args.getArgumentCount(); boolean superFirst = false; int thisIndex = -1; FIND_SUPER_OR_THIS: { //search all nodes except last for 'this' or 'super'. will be at: (node 0 | node 1 | nowhere) //this is an ASTPrimarySuffix with a null image and does not have child (which will be of type ASTArguments) //this is an ASTPrimaryPrefix with a null image and an ASTName that has a null image //super is an ASTPrimarySuffix with a null image and does not have child (which will be of type ASTArguments) //super is an ASTPrimaryPrefix with a non-null image for (int x = 0; x < i - 1; x++) { Node child = node.jjtGetChild(x); if (child instanceof ASTPrimarySuffix) { //check suffix type match ASTPrimarySuffix child2 = (ASTPrimarySuffix) child; // String name = getNameFromSuffix((ASTPrimarySuffix)child); // System.out.println("found name suffix of : " + name); if (child2.getImage() == null && child2.jjtGetNumChildren() == 0) { thisIndex = x; break; } //could be super, could be this. currently we cant tell difference so we miss super when //XYZ.ClassName.super.method(); //still works though. } else if (child instanceof ASTPrimaryPrefix) { //check prefix type match ASTPrimaryPrefix child2 = (ASTPrimaryPrefix) child; if (getNameFromPrefix(child2) == null) { if (child2.getImage() == null) { thisIndex = x; break; } else {//happens when super is used [super.method(): image = 'method'] superFirst = true; thisIndex = x; //the true super is at an unusable index because super.method() has only 2 nodes [method=0,()=1] //as opposed to the 3 you might expect and which this.method() actually has. [this=0,method=1.()=2] break; } } } // else{ // System.err.println("Bad Format error"); //throw exception, quit evaluating this compilation node // } } } if (thisIndex != -1) { // System.out.println("Found this or super: " + thisIndex); //Hack that must be removed if and when the patters of super.method() begins to logically match the rest of the patterns !!! if (superFirst) { //this is when super is the first node of statement. no qualifiers, all variables or method // System.out.println("super first"); FIRSTNODE:{ ASTPrimaryPrefix child = (ASTPrimaryPrefix) node.jjtGetChild(0); String name = child.getImage();//special case if (i == 2) { //last named node = method name methodName = name; } else { //not the last named node so its only var name varNames.add(name); } } OTHERNODES:{ //variables for (int x = 1; x < i - 1; x++) { Node child = node.jjtGetChild(x); ASTPrimarySuffix ps = (ASTPrimarySuffix) child; if (!ps.isArguments()) { String name = ((ASTPrimarySuffix) child).getImage(); if (x == i - 2) {//last node methodName = name; } else {//not the last named node so its only var name varNames.add(name); } } } } } else {//not super call FIRSTNODE:{ if (thisIndex == 1) {//qualifiers in node 0 ASTPrimaryPrefix child = (ASTPrimaryPrefix) node.jjtGetChild(0); String toParse = getNameFromPrefix(child); // System.out.println("parsing for class/package names in : " + toParse); java.util.StringTokenizer st = new java.util.StringTokenizer(toParse, "."); while (st.hasMoreTokens()) { packagesAndClasses.add(st.nextToken()); } } } OTHERNODES:{ //other methods called in this statement are grabbed here //this is at 0, then no Qualifiers //this is at 1, the node 0 contains qualifiers for (int x = thisIndex + 1; x < i - 1; x++) {//everything after this is var name or method name ASTPrimarySuffix child = (ASTPrimarySuffix) node.jjtGetChild(x); if (!child.isArguments()) { //skip the () of method calls String name = child.getImage(); // System.out.println("Found suffix: " + suffixName); if (x == i - 2) { methodName = name; } else { varNames.add(name); } } } } } } else { //if no this or super found, everything is method name or variable //System.out.println("no this found:"); FIRSTNODE:{ //variable names are in the prefix + the first method call [a.b.c.x()] ASTPrimaryPrefix child = (ASTPrimaryPrefix) node.jjtGetChild(0); String toParse = getNameFromPrefix(child); // System.out.println("parsing for var names in : " + toParse); java.util.StringTokenizer st = new java.util.StringTokenizer(toParse, "."); while (st.hasMoreTokens()) { String value = st.nextToken(); if (!st.hasMoreTokens()) { if (i == 2) {//if this expression is 2 nodes long, then the last part of prefix is method name methodName = value; } else { varNames.add(value); } } else { //variable name varNames.add(value); } } } OTHERNODES:{ //other methods called in this statement are grabbed here for (int x = 1; x < i - 1; x++) { ASTPrimarySuffix child = (ASTPrimarySuffix) node.jjtGetChild(x); if (!child.isArguments()) { String name = child.getImage(); if (x == i - 2) { methodName = name; } else { varNames.add(name); } } } } } meth = new MethodInvocation(node, packagesAndClasses, varNames, methodName, numOfArguments, superFirst); } } return meth; } public void show() { System.out.println("<MethodInvocation>"); System.out.println(" <Qualifiers>"); for (String name: getQualifierNames()) { System.out.println(" " + name); } System.out.println(" </Qualifiers>"); System.out.println(" <Super>" + isSuper() + "</Super>"); System.out.println(" <References>"); for (String name: getReferenceNames()) { System.out.println(" " + name); } System.out.println(" </References>"); System.out.println(" <Name>" + getName() + "</Name>"); System.out.println("</MethodInvocation>"); } } private static final class ConstructorInvocation { private ASTExplicitConstructorInvocation m_Eci; private String name; private int count = 0; public ConstructorInvocation(ASTExplicitConstructorInvocation eci) { m_Eci = eci; List<ASTArguments> l = new ArrayList<ASTArguments>(); eci.findChildrenOfType(ASTArguments.class, l); if (!l.isEmpty()) { ASTArguments aa = l.get(0); count = aa.getArgumentCount(); } name = eci.getImage(); } public ASTExplicitConstructorInvocation getASTExplicitConstructorInvocation() { return m_Eci; } public int getArgumentCount() { return count; } public String getName() { return name; } } private static final class MethodHolder { private ASTMethodDeclarator amd; private boolean dangerous; private String called; public MethodHolder(ASTMethodDeclarator amd) { this.amd = amd; } public void setCalledMethod(String name) { this.called = name; } public String getCalled() { return this.called; } public ASTMethodDeclarator getASTMethodDeclarator() { return amd; } public boolean isDangerous() { return dangerous; } public void setDangerous() { dangerous = true; } } private final class ConstructorHolder { private ASTConstructorDeclaration m_Cd; private boolean m_Dangerous; private ConstructorInvocation m_Ci; private boolean m_CiInitialized; public ConstructorHolder(ASTConstructorDeclaration cd) { m_Cd = cd; } public ASTConstructorDeclaration getASTConstructorDeclaration() { return m_Cd; } public ConstructorInvocation getCalledConstructor() { if (!m_CiInitialized) { initCI(); } return m_Ci; } public ASTExplicitConstructorInvocation getASTExplicitConstructorInvocation() { ASTExplicitConstructorInvocation eci = null; if (!m_CiInitialized) { initCI(); } if (m_Ci != null) { eci = m_Ci.getASTExplicitConstructorInvocation(); } return eci; } private void initCI() { List<ASTExplicitConstructorInvocation> expressions = new ArrayList<ASTExplicitConstructorInvocation>(); m_Cd.findChildrenOfType(ASTExplicitConstructorInvocation.class, expressions); //only 1... if (!expressions.isEmpty()) { ASTExplicitConstructorInvocation eci = expressions.get(0); m_Ci = new ConstructorInvocation(eci); //System.out.println("Const call " + eci.getImage()); //super or this??? } m_CiInitialized = true; } public boolean isDangerous() { return m_Dangerous; } public void setDangerous(boolean dangerous) { m_Dangerous = dangerous; } } private static final int compareNodes(SimpleNode n1, SimpleNode n2) { int l1 = n1.getBeginLine(); int l2 = n2.getBeginLine(); if (l1 == l2) { return n1.getBeginColumn() - n2.getBeginColumn(); } return l1 - l2; } private static class MethodHolderComparator implements Comparator<MethodHolder> { public int compare(MethodHolder o1, MethodHolder o2) { return compareNodes(o1.getASTMethodDeclarator(), o2.getASTMethodDeclarator()); } } private static class ConstructorHolderComparator implements Comparator<ConstructorHolder> { public int compare(ConstructorHolder o1, ConstructorHolder o2) { return compareNodes(o1.getASTConstructorDeclaration(), o2.getASTConstructorDeclaration()); } } /** * 1 package per class. holds info for evaluating a single class. */ private static class EvalPackage { public EvalPackage() { } public EvalPackage(String className) { m_ClassName = className; calledMethods = new ArrayList<MethodInvocation>();//meths called from constructor allMethodsOfClass = new TreeMap<MethodHolder, List<MethodInvocation>>(new MethodHolderComparator()); calledConstructors = new ArrayList<ConstructorInvocation>();//all constructors called from constructor allPrivateConstructorsOfClass = new TreeMap<ConstructorHolder, List<MethodInvocation>>(new ConstructorHolderComparator()); } public String m_ClassName; public List<MethodInvocation> calledMethods; public Map<MethodHolder, List<MethodInvocation>> allMethodsOfClass; public List<ConstructorInvocation> calledConstructors; public Map<ConstructorHolder, List<MethodInvocation>> allPrivateConstructorsOfClass; } private static final class NullEvalPackage extends EvalPackage { public NullEvalPackage() { m_ClassName = ""; calledMethods = Collections.emptyList(); allMethodsOfClass = Collections.emptyMap(); calledConstructors = Collections.emptyList(); allPrivateConstructorsOfClass = Collections.emptyMap(); } } private static final NullEvalPackage nullEvalPackage = new NullEvalPackage(); /** * 1 package per class. */ private final List<EvalPackage> evalPackages = new ArrayList<EvalPackage>();//could use java.util.Stack private EvalPackage getCurrentEvalPackage() { return evalPackages.get(evalPackages.size() - 1); } /** * Adds and evaluation package and makes it current */ private void putEvalPackage(EvalPackage ep) { evalPackages.add(ep); } private void removeCurrentEvalPackage() { evalPackages.remove(evalPackages.size() - 1); } private void clearEvalPackages() { evalPackages.clear(); } /** * This check must be evaluated independently for each class. Inner classes * get their own EvalPackage in order to perform independent evaluation. */ private Object visitClassDec(ASTClassOrInterfaceDeclaration node, Object data) { String className = node.getImage(); if (!node.isFinal()) { putEvalPackage(new EvalPackage(className)); } else { putEvalPackage(nullEvalPackage); } //store any errors caught from other passes. super.visit(node, data); //skip this class if it has no evaluation package if (!(getCurrentEvalPackage() instanceof NullEvalPackage)) { //evaluate danger of all methods in class, this method will return false when all methods have been evaluated while (evaluateDangerOfMethods(getCurrentEvalPackage().allMethodsOfClass)) { } //NOPMD //evaluate danger of constructors evaluateDangerOfConstructors1(getCurrentEvalPackage().allPrivateConstructorsOfClass, getCurrentEvalPackage().allMethodsOfClass.keySet()); while (evaluateDangerOfConstructors2(getCurrentEvalPackage().allPrivateConstructorsOfClass)) { } //NOPMD //get each method called on this object from a non-private constructor, if its dangerous flag it for (MethodInvocation meth: getCurrentEvalPackage().calledMethods) { //check against each dangerous method in class for (MethodHolder h: getCurrentEvalPackage().allMethodsOfClass.keySet()) { if (h.isDangerous()) { String methName = h.getASTMethodDeclarator().getImage(); int count = h.getASTMethodDeclarator().getParameterCount(); if (methName.equals(meth.getName()) && meth.getArgumentCount() == count) { addViolation(data, meth.getASTPrimaryExpression(), "method '" + h.getCalled() + "'"); } } } } //get each unsafe private constructor, and check if its called from any non private constructors for (ConstructorHolder ch: getCurrentEvalPackage().allPrivateConstructorsOfClass.keySet()) { if (ch.isDangerous()) { //if its dangerous check if its called from any non-private constructors //System.out.println("visitClassDec Evaluating dangerous constructor with " + ch.getASTConstructorDeclaration().getParameterCount() + " params"); int paramCount = ch.getASTConstructorDeclaration().getParameterCount(); for (ConstructorInvocation ci: getCurrentEvalPackage().calledConstructors) { if (ci.getArgumentCount() == paramCount) { //match name super / this !? addViolation(data, ci.getASTExplicitConstructorInvocation(), "constructor"); } } } } } //finished evaluating this class, move up a level removeCurrentEvalPackage(); return data; } /** * Check the methods called on this class by each of the methods on this * class. If a method calls an unsafe method, mark the calling method as * unsafe. This changes the list of unsafe methods which necessitates * another pass. Keep passing until you make a clean pass in which no * methods are changed to unsafe. * For speed it is possible to limit the number of passes. * <p/> * Impossible to tell type of arguments to method, so forget method matching * on types. just use name and num of arguments. will be some false hits, * but oh well. * * @todo investigate limiting the number of passes through config. */ private boolean evaluateDangerOfMethods(Map<MethodHolder, List<MethodInvocation>> classMethodMap) { //check each method if it calls overridable method boolean found = false; for (Map.Entry<MethodHolder, List<MethodInvocation>> entry: classMethodMap.entrySet()) { MethodHolder h = entry.getKey(); List<MethodInvocation> calledMeths = entry.getValue(); for (Iterator<MethodInvocation> calledMethsIter = calledMeths.iterator(); calledMethsIter.hasNext() && !h.isDangerous();) { //if this method matches one of our dangerous methods, mark it dangerous MethodInvocation meth = calledMethsIter.next(); //System.out.println("Called meth is " + meth); for (MethodHolder h3: classMethodMap.keySet()) { //need to skip self here h == h3 if (h3.isDangerous()) { String matchMethodName = h3.getASTMethodDeclarator().getImage(); int matchMethodParamCount = h3.getASTMethodDeclarator().getParameterCount(); //System.out.println("matching " + matchMethodName + " to " + meth.getName()); if (matchMethodName.equals(meth.getName()) && matchMethodParamCount == meth.getArgumentCount()) { h.setDangerous(); h.setCalledMethod(matchMethodName); found = true; break; } } } } } return found; } /** * marks constructors dangerous if they call any dangerous methods * Requires only a single pass as methods are already marked * * @todo optimize by having methods already evaluated somehow!? */ private void evaluateDangerOfConstructors1(Map<ConstructorHolder, List<MethodInvocation>> classConstructorMap, Set<MethodHolder> evaluatedMethods) { //check each constructor in the class for (Map.Entry<ConstructorHolder, List<MethodInvocation>> entry: classConstructorMap.entrySet()) { ConstructorHolder ch = entry.getKey(); if (!ch.isDangerous()) {//if its not dangerous then evaluate if it should be //if it calls dangerous method mark it as dangerous List<MethodInvocation> calledMeths = entry.getValue(); //check each method it calls for (Iterator<MethodInvocation> calledMethsIter = calledMeths.iterator(); calledMethsIter.hasNext() && !ch.isDangerous();) {//but thee are diff objects which represent same thing but were never evaluated, they need reevaluation MethodInvocation meth = calledMethsIter.next();//CCE String methName = meth.getName(); int methArgCount = meth.getArgumentCount(); //check each of the already evaluated methods: need to optimize this out for (MethodHolder h: evaluatedMethods) { if (h.isDangerous()) { String matchName = h.getASTMethodDeclarator().getImage(); int matchParamCount = h.getASTMethodDeclarator().getParameterCount(); if (methName.equals(matchName) && (methArgCount == matchParamCount)) { ch.setDangerous(true); //System.out.println("evaluateDangerOfConstructors1 setting dangerous constructor with " + ch.getASTConstructorDeclaration().getParameterCount() + " params"); break; } } } } } } } /** * Constructor map should contain a key for each private constructor, and * maps to a List which contains all called constructors of that key. * marks dangerous if call dangerous private constructor * we ignore all non-private constructors here. That is, the map passed in * should not contain any non-private constructors. * we return boolean in order to limit the number of passes through this method * but it seems as if we can forgo that and just process it till its done. */ private boolean evaluateDangerOfConstructors2(Map<ConstructorHolder, List<MethodInvocation>> classConstructorMap) { boolean found = false;//triggers on danger state change //check each constructor in the class for (ConstructorHolder ch: classConstructorMap.keySet()) { ConstructorInvocation calledC = ch.getCalledConstructor(); if (calledC == null || ch.isDangerous()) { continue; } //if its not dangerous then evaluate if it should be //if it calls dangerous constructor mark it as dangerous int cCount = calledC.getArgumentCount(); for (Iterator<ConstructorHolder> innerConstIter = classConstructorMap.keySet().iterator(); innerConstIter.hasNext() && !ch.isDangerous();) { //forget skipping self because that introduces another check for each, but only 1 hit ConstructorHolder h2 = innerConstIter.next(); if (h2.isDangerous()) { int matchConstArgCount = h2.getASTConstructorDeclaration().getParameterCount(); if (matchConstArgCount == cCount) { ch.setDangerous(true); found = true; //System.out.println("evaluateDangerOfConstructors2 setting dangerous constructor with " + ch.getASTConstructorDeclaration().getParameterCount() + " params"); } } } } return found; } public Object visit(ASTCompilationUnit node, Object data) { clearEvalPackages(); return super.visit(node, data); } public Object visit(ASTEnumDeclaration node, Object data) { // just skip Enums return data; } /** * This check must be evaluated independelty for each class. Inner classses * get their own EvalPackage in order to perform independent evaluation. */ public Object visit(ASTClassOrInterfaceDeclaration node, Object data) { if (!node.isInterface()) { return visitClassDec(node, data); } else { putEvalPackage(nullEvalPackage); Object o = super.visit(node, data);//interface may have inner classes, possible? if not just skip whole interface removeCurrentEvalPackage(); return o; } } /** * Non-private constructor's methods are added to a list for later safety * evaluation. Non-private constructor's calls on private constructors * are added to a list for later safety evaluation. Private constructors * are added to a list so their safety to be called can be later evaluated. * <p/> * Note: We are not checking private constructor's calls on non-private * constructors because all non-private constructors will be evaluated for * safety anyway. This means we wont flag a private constructor as unsafe * just because it calls an unsafe public constructor. We want to show only * 1 instance of an error, and this would be 2 instances of the same error. * * @todo eliminate the redundency */ public Object visit(ASTConstructorDeclaration node, Object data) { if (!(getCurrentEvalPackage() instanceof NullEvalPackage)) {//only evaluate if we have an eval package for this class List<MethodInvocation> calledMethodsOfConstructor = new ArrayList<MethodInvocation>(); ConstructorHolder ch = new ConstructorHolder(node); addCalledMethodsOfNode(node, calledMethodsOfConstructor, getCurrentEvalPackage().m_ClassName); if (!node.isPrivate()) { //these calledMethods are what we will evaluate for being called badly getCurrentEvalPackage().calledMethods.addAll(calledMethodsOfConstructor); //these called private constructors are what we will evaluate for being called badly //we add all constructors invoked by non-private constructors //but we are only interested in the private ones. We just can't tell the difference here ASTExplicitConstructorInvocation eci = ch.getASTExplicitConstructorInvocation(); if (eci != null && eci.isThis()) { getCurrentEvalPackage().calledConstructors.add(ch.getCalledConstructor()); } } else { //add all private constructors to list for later evaluation on if they are safe to call from another constructor //store this constructorHolder for later evaluation getCurrentEvalPackage().allPrivateConstructorsOfClass.put(ch, calledMethodsOfConstructor); } } return super.visit(node, data); } /** * Create a MethodHolder to hold the method. * Store the MethodHolder in the Map as the key * Store each method called by the current method as a List in the Map as the Object */ public Object visit(ASTMethodDeclarator node, Object data) { if (!(getCurrentEvalPackage() instanceof NullEvalPackage)) {//only evaluate if we have an eval package for this class AccessNode parent = (AccessNode) node.jjtGetParent(); MethodHolder h = new MethodHolder(node); if (!parent.isAbstract() && !parent.isPrivate() && !parent.isStatic() && !parent.isFinal()) { //Skip abstract methods, have a separate rule for that h.setDangerous();//this method is overridable ASTMethodDeclaration decl = node.getFirstParentOfType(ASTMethodDeclaration.class); h.setCalledMethod(decl.getMethodName()); } List<MethodInvocation> l = new ArrayList<MethodInvocation>(); addCalledMethodsOfNode((SimpleNode) parent, l, getCurrentEvalPackage().m_ClassName); getCurrentEvalPackage().allMethodsOfClass.put(h, l); } return super.visit(node, data); } private static void addCalledMethodsOfNode(AccessNode node, List<MethodInvocation> calledMethods, String className) { List<ASTPrimaryExpression> expressions = new ArrayList<ASTPrimaryExpression>(); node.findChildrenOfType(ASTPrimaryExpression.class, expressions, false); addCalledMethodsOfNodeImpl(expressions, calledMethods, className); } /** * Adds all methods called on this instance from within this Node. */ private static void addCalledMethodsOfNode(SimpleNode node, List<MethodInvocation> calledMethods, String className) { List<ASTPrimaryExpression> expressions = new ArrayList<ASTPrimaryExpression>(); node.findChildrenOfType(ASTPrimaryExpression.class, expressions); addCalledMethodsOfNodeImpl(expressions, calledMethods, className); } private static void addCalledMethodsOfNodeImpl(List<ASTPrimaryExpression> expressions, List<MethodInvocation> calledMethods, String className) { for (ASTPrimaryExpression ape: expressions) { MethodInvocation meth = findMethod(ape, className); if (meth != null) { //System.out.println("Adding call " + methName); calledMethods.add(meth); } } } /** * @return A method call on the class passed in, or null if no method call * is found. * @todo Need a better way to match the class and package name to the actual * method being called. */ private static MethodInvocation findMethod(ASTPrimaryExpression node, String className) { if (node.jjtGetNumChildren() > 0 && node.jjtGetChild(0).jjtGetNumChildren() > 0 && node.jjtGetChild(0).jjtGetChild(0) instanceof ASTLiteral) { return null; } MethodInvocation meth = MethodInvocation.getMethod(node); boolean found = false; // if(meth != null){ // meth.show(); // } if (meth != null) { //if it's a call on a variable, or on its superclass ignore it. if ((meth.getReferenceNames().size() == 0) && !meth.isSuper()) { //if this list does not contain our class name, then its not referencing our class //this is a cheezy test... but it errs on the side of less false hits. List<String> packClass = meth.getQualifierNames(); if (!packClass.isEmpty()) { for (String name: packClass) { if (name.equals(className)) { found = true; break; } } } else { found = true; } } } return found ? meth : null; } /** * ASTPrimaryPrefix has name in child node of ASTName */ private static String getNameFromPrefix(ASTPrimaryPrefix node) { String name = null; //should only be 1 child, if more I need more knowledge if (node.jjtGetNumChildren() == 1) { //safety check Node nnode = node.jjtGetChild(0); if (nnode instanceof ASTName) { //just as easy as null check and it should be an ASTName anyway name = ((ASTName) nnode).getImage(); } } return name; } }

The table below shows all metrics for ConstructorCallsOverridableMethod.java.

MetricValueDescription
BLOCKS147.00Number of blocks
BLOCK_COMMENT 0.00Number of block comment lines
COMMENTS268.00Comment lines
COMMENT_DENSITY 0.65Comment density
COMPARISONS76.00Number of comparison operators
CYCLOMATIC129.00Cyclomatic complexity
DECL_COMMENTS16.00Comments in declarations
DOC_COMMENT202.00Number of javadoc comment lines
ELOC415.00Effective lines of code
EXEC_COMMENTS46.00Comments in executable code
EXITS98.00Procedure exits
FUNCTIONS50.00Number of function declarations
HALSTEAD_DIFFICULTY 0.44Halstead difficulty
HALSTEAD_EFFORT 0.00Halstead effort
INTERFACE_COMPLEXITY101.00Interface complexity
JAVA0001 0.00JAVA0001 Package name does not contain only lower case letters
JAVA0002 0.00JAVA0002 Package name does not begin with a top level domain name or country code
JAVA0003 0.00JAVA0003 Minimize use of on-demand (.*) imports
JAVA0004 0.00JAVA0004 Unnecessary import from java.lang
JAVA0005 1.00JAVA0005 Imports not in specified order
JAVA0006 0.00JAVA0006 Empty finally block
JAVA0007 5.00JAVA0007 Should not declare public field
JAVA0008 0.00JAVA0008 Empty catch block
JAVA0009 0.00JAVA0009 Protected member in final class
JAVA0010 0.00JAVA0010 Non-instantiable class does not contain a non-private static member
JAVA0011 0.00JAVA0011 Abstract class does not contain an abstract method
JAVA0012 0.00JAVA0012 Non-constructor method with same name as declaring class
JAVA0013 0.00JAVA0013 Non-blank final field is not static
JAVA0014 0.00JAVA0014 Class with only static members has non-private constructor
JAVA0015 0.00JAVA0015 Package class contains public nested type
JAVA0016 0.00JAVA0016 Abstract class contains public constructor
JAVA0017 0.00JAVA0017 Class name does not have required form
JAVA0018 0.00JAVA0018 Method name does not have required form
JAVA0019 0.00JAVA0019 Interface name does not have required form
JAVA0020 0.00JAVA0020 Field name does not have required form
JAVA0021 0.00JAVA0021 Interface method name does not have required form
JAVA0022 0.00JAVA0022 Static final field name does not have required form
JAVA0023 0.00JAVA0023 Empty finalize method
JAVA0024 0.00JAVA0024 Empty class
JAVA0025 0.00JAVA0025 Method override is empty
JAVA0026 0.00JAVA0026 Finalize method with parameters
JAVA0029 0.00JAVA0029 Private method not used
JAVA0030 0.00JAVA0030 Private field not used
JAVA0031 0.00JAVA0031 Case statement not properly closed
JAVA0032 0.00JAVA0032 Switch statement missing default
JAVA0033 0.00JAVA0033 default: not last case in switch statement
JAVA0034 0.00JAVA0034 Missing braces in if statement
JAVA0035 0.00JAVA0035 Missing braces in for statement
JAVA0036 0.00JAVA0036 Missing braces in while statement
JAVA0038 0.00JAVA0038 Non-case label in switch statement
JAVA0039 0.00JAVA0039 Break statement with label
JAVA0040 0.00JAVA0040 Switch statement contains N cases (maximum: M)
JAVA0041 0.00JAVA0041 Nested synchronized block
JAVA0042 0.00JAVA0042 Empty synchronized statement
JAVA0043 1.00JAVA0043 Inner class does not use outer class
JAVA0044 0.00JAVA0044 Serializable class with no instance variables
JAVA0045 0.00JAVA0045 Serializable class with only transient fields
JAVA0046 0.00JAVA0046 Name of class not derived from Exception ends with 'Exception'
JAVA0047 0.00JAVA0047 Serializable class derives from invalid base class
JAVA0048 0.00JAVA0048 Name of class derived from Exception does not end with 'Exception'
JAVA004913.00JAVA0049 Nested block at depth N (maximum: M)
JAVA0050 0.00JAVA0050 Class derives from java.lang.Error
JAVA0051 0.00JAVA0051 Class derives from java.lang.RuntimeException
JAVA0052 0.00JAVA0052 Class derives from java.lang.Throwable
JAVA0053 7.00JAVA0053 Unused label
JAVA0054 0.00JAVA0054 Inheritance depth N exceeds maximum M
JAVA0055 0.00JAVA0055 Class should be interface
JAVA0056 0.00JAVA0056 Unnecessary abstract modifier for interface or annotation
JAVA0057 0.00JAVA0057 Unnecessary default constructor
JAVA0058 0.00JAVA0058 Constructor calls super()
JAVA0059 0.00JAVA0059 Method override only calls super()
JAVA0061 0.00JAVA0061 Inaccessible member in anonymous class
JAVA0062 0.00JAVA0062 Public class missing public member or protected constructor
JAVA0063 0.00JAVA0063 Identifier name should not contain '$'
JAVA0064 0.00JAVA0064 N variations of identifier name (maximum: M)
JAVA0065 1.00JAVA0065 Unnecessary final modifier for method in final class
JAVA0066 0.00JAVA0066 Unnecessary modifier for interface nested type
JAVA0067 0.00JAVA0067 Array descriptor on identifier name
JAVA0068 0.00JAVA0068 Modifiers not declared in recommended order
JAVA0071 0.00JAVA0071 Strings compared with ==
JAVA0073 0.00JAVA0073 Integer division in floating-point context
JAVA0074 0.00JAVA0074 Use of Object.notify()
JAVA0075 0.00JAVA0075 Method parameter hides field
JAVA0076 0.00JAVA0076 Use of magic number
JAVA0077 0.00JAVA0077 Private field not used in declaring class
JAVA0078 0.00JAVA0078 Floating point values compared with ==
JAVA0079 0.00JAVA0079 Use of instance to reference static member
JAVA0080 0.00JAVA0080 Import declaration not used
JAVA0081 0.00JAVA0081 Boolean literal in comparison
JAVA0082 1.00JAVA0082 Unnecessary widening cast
JAVA0083 0.00JAVA0083 Unnecessary instanceof test
JAVA0084 0.00JAVA0084 Should use compound assignment operator
JAVA0085 0.00JAVA0085 Use of sun.* class
JAVA0087 0.00JAVA0087 Use of Thread.sleep()
JAVA0089 0.00JAVA0089 Use of restricted package
JAVA0092 0.00JAVA0092 Use of restricted type
JAVA0093 0.00JAVA0093 Redundant assignment
JAVA0094 0.00JAVA0094 Field hides a superclass field
JAVA0095 0.00JAVA0095 Uninitialized private field
JAVA0096 0.00JAVA0096 Field in nested class hides outer field
JAVA0098 1.00JAVA0098 Minimize use of implicit field initializers
JAVA0100 0.00JAVA0100 Class contains N non-final fields (maximum: M)
JAVA0101 0.00JAVA0101 Unnecessary modifier for field in interface
JAVA0102 0.00JAVA0102 Last statement in finalize() not super.finalize()
JAVA0103 0.00JAVA0103 Explicit call to finalize()
JAVA0104 0.00JAVA0104 finalize() only calls super.finalize()
JAVA0105 0.00JAVA0105 Duplicate import declaration
JAVA0106 0.00JAVA0106 Unnecessary import from current package
JAVA010813.00JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
JAVA0109 0.00JAVA0109 Incorrect javadoc: no parameter 'parameter'
JAVA0110 7.00JAVA0110 Incorrect javadoc: no @return tag
JAVA0111 0.00JAVA0111 Incorrect javadoc: @return tag for void method
JAVA0112 0.00JAVA0112 Incorrect javadoc: no exception 'exception' in throws
JAVA0113 2.00JAVA0113 Incorrect javadoc: no @author tag
JAVA0114 3.00JAVA0114 Incorrect javadoc: no @version tag
JAVA0115 0.00JAVA0115 Incorrect javadoc: no @throws or @exception tag for 'exception'
JAVA0116 5.00JAVA0116 Missing javadoc: field 'field'
JAVA011727.00JAVA0117 Missing javadoc: method 'method'
JAVA0118 0.00JAVA0118 Missing javadoc: type 'type'
JAVA0119 0.00JAVA0119 Control variable changed within body of for loop
JAVA0123 3.00JAVA0123 Use all three components of for loop
JAVA0125 0.00JAVA0125 Continue statement with label
JAVA0126 0.00JAVA0126 Method declares unchecked exception in throws
JAVA0128 6.00JAVA0128 Public constructor in non-public class
JAVA0130 3.00JAVA0130 Non-static method does not use instance fields
JAVA0131 0.00JAVA0131 Compatible method does not override base
JAVA0132 0.00JAVA0132 Method overload with compatible signature
JAVA0133 0.00JAVA0133 Non-synchronized method overrides synchronized method
JAVA0135 0.00JAVA0135 Only one of Object.equals and Object.hashCode defined: missing 'method'
JAVA0136 0.00JAVA0136 N methods defined in class (maximum: M)
JAVA0137 0.00JAVA0137 Non-abstract class missing constructor
JAVA0138 1.00JAVA0138 N parameters defined for method (maximum: M)
JAVA0139 0.00JAVA0139 Definition of main other than public static void main(java.lang.String[])
JAVA0141 0.00JAVA0141 Unnecessary modifier for method in interface
JAVA0143 0.00JAVA0143 Synchronized method
JAVA014420.00JAVA0144 Line exceeds maximum M characters
JAVA0145117.00JAVA0145 Tab character used in source file
JAVA0150 0.00JAVA0150 java.lang.Error (or subclass) thrown
JAVA0153 0.00JAVA0153 Inefficient conversion of integer to string
JAVA0159 0.00JAVA0159 Inefficient conversion of string to integer
JAVA0160 0.00JAVA0160 Method does not throw specified exception
JAVA0161 0.00JAVA0161 Conditional wait() not in loop
JAVA0163 0.00JAVA0163 Empty statement
JAVA0165 0.00JAVA0165 Conflicting return statement in finally block
JAVA0166 0.00JAVA0166 Generic exception caught
JAVA0167 0.00JAVA0167 ThreadDeath not rethrown
JAVA0169 0.00JAVA0169 Unnecessary catch block: exception 'exception'
JAVA0170 0.00JAVA0170 Caught exception not derived from java.lang.Exception
JAVA0171 0.00JAVA0171 Unused local variable
JAVA0173 0.00JAVA0173 Unused method parameter
JAVA0174 0.00JAVA0174 Assigned local variable never used
JAVA0175 0.00JAVA0175 Successive assignment to variable
JAVA0176 0.00JAVA0176 Local variable name does not have required form
JAVA0177 0.00JAVA0177 Variable declaration missing initializer
JAVA0179 0.00JAVA0179 Local variable hides visible field
JAVA0233 0.00JAVA0233 Definition of serialVersionUID other than 'private static final long serialVersionUID'
JAVA0234 0.00JAVA0234 Class is Serializable but does not define serialVersionUID
JAVA0235 0.00JAVA0235 Class defines serialVersionUID but does not implement Serializable
JAVA0236 0.00JAVA0236 Attempt to clone an object which does not implement Cloneable
JAVA0237 0.00JAVA0237 Class implements Cloneable but does not have public clone method
JAVA0238 0.00JAVA0238 Clone method does not call super.clone()
JAVA0239 0.00JAVA0239 Class declares 'readObject' or 'writeObject' but does not implement Serializable
JAVA0240 0.00JAVA0240 Serializable class which declares readObject or writeObject but not both
JAVA0241 0.00JAVA0241 'readObject' or 'writeObject' should be declared private in Serializable class
JAVA0242 0.00JAVA0242 Transient field in non-Serializable class
JAVA0243 0.00JAVA0243 'readResolve' or 'writeReplace' should be declared private or protected
JAVA0244 0.00JAVA0244 Field or method name in subclass differs only by case from inherited field or method
JAVA0245 0.00JAVA0245 JUnit TestCase with non-trivial constructor
JAVA0246 0.00JAVA0246 JUnit assertXXX statement missing message parameter
JAVA0247 0.00JAVA0247 JUnit 'setUp()' and 'tearDown()' should call super method
JAVA0248 0.00JAVA0248 JUnit method 'setUp' or 'tearDown' with incorrect signature
JAVA0249 0.00JAVA0249 JUnit TestCase 'suite()' should be declared static
JAVA0250 0.00JAVA0250 JUnit TestCase declares testXXX method with incorrect signature
JAVA0251 0.00JAVA0251 Use '%n' for line breaks in printf/format for platform independence
JAVA0252 0.00JAVA0252 'enum' is a Java 1.5 reserved word
JAVA0253 0.00JAVA0253 Not all enum constants consumed in switch statement
JAVA0254 3.00JAVA0254 Use enhanced for loop construct instead of Iterator
JAVA0255 0.00JAVA0255 Result of method invocation not used
JAVA0256 2.00JAVA0256 Assignment of external collection/array to field
JAVA0257 0.00JAVA0257 Use of 'Constant Interface' anti-pattern
JAVA0258 0.00JAVA0258 Implement Iterable for foreach compatibility
JAVA0259 2.00JAVA0259 Return of collection/array field
JAVA0260 0.00JAVA0260 Use 'enum' instead of Enumerated Type pattern
JAVA0261 0.00JAVA0261 Use specialized Enum collection types
JAVA0262 0.00JAVA0262 Use of char in integer context
JAVA0263 0.00JAVA0263 Long literal ends with 'l' instead of 'L'
JAVA0264 0.00JAVA0264 Integer math in long context - check for overflow
JAVA0265 0.00JAVA0265 Use of Throwable.printStackTrace()
JAVA026610.00JAVA0266 Use of System.out
JAVA0267 0.00JAVA0267 Use of System.err
JAVA0269 0.00JAVA0269 Contents of StringBuffer never used
JAVA0270 0.00JAVA0270 Use Java 5.0 enhanced for loop construct to iterate over all elements in an array
JAVA0271 0.00JAVA0271 Minimize use of on-demand (.*) static imports
JAVA0272 0.00JAVA0272 Thread.run() called
JAVA0273 0.00JAVA0273 Non-final derivative of Thread calls start() in constructor
JAVA0274 0.00JAVA0274 Serializable class has a synchronized readObject()
JAVA0275 0.00JAVA0275 Serializable class has a synchronized writeObject() and no other synchronized methods
JAVA0276 0.00JAVA0276 Unnecessary use of String constructor
JAVA0277 0.00JAVA0277 Iterator.next() implementation does not throw NoSuchElementException
JAVA0278 0.00JAVA0278 Unnecessary use of Boolean constructor
JAVA0279 0.00JAVA0279 Serialization method readObject or readObjectNoData calls an overridable method
JAVA0280 0.00JAVA0280 IllegalMonitorStateException caught
JAVA0281 0.00JAVA0281 Iterator.next() not called in loop
JAVA0282 0.00JAVA0282 Call to Iterator.next() in loop which does not test Iterator.hasNext()
JAVA0283 0.00JAVA0283 Control variable not updated in loop body
JAVA0284 0.00JAVA0284 Explicit garbage collection
JAVA0285 0.00JAVA0285 Dereference of potentially null variable
JAVA0286 0.00JAVA0286 Dereference of null variable
JAVA0287 0.00JAVA0287 Unnecessary null check
JAVA0288 0.00JAVA0288 Inconsistent null check
JAVA0289 6.00null
LINES893.00Number of lines in the source file
LINE_COMMENT66.00Number of line comments
LOC555.00Lines of code
LOGICAL_LINES271.00Number of statements
LOOPS11.00Number of loops
NEST_DEPTH 9.00Maximum nesting depth
OPERANDS1304.00Number of operands
OPERATORS2510.00Number of operators
PARAMS48.00Number of formal parameter declarations
PROGRAM_LENGTH3814.00Halstead program length
PROGRAM_VOCAB421.00Halstead program vocabulary
PROGRAM_VOLUME 0.00Halstead program volume
RETURNS53.00Number of return points from functions
SIZE41244.00Size of the file in bytes
UNIQUE_OPERANDS374.00Number of unique operands
UNIQUE_OPERATORS47.00Number of unique operators
WHITESPACE70.00Number of whitespace lines