Maisqual Rules

From Maisqual Wiki

Jump to: navigation, search

Rules are associated to practices that have an impact on some characteristic of quality.

We list hereafter the rule checks that we decided to include in our data sets, with information about their associated practices and further references. The categories defined in the rule sets are mapped to the ISO 9126 decomposition of quality (analysability, changeability, stability, testability, etc.) and to development concerns (programming techniques, architecture, etc.).

Many of these rules can be linked to coding conventions published by standardisation organisms like MISRA[1] (the Motor Industry Software Reliability Association, which C rule set is well spread) or CERT[2] (Carnegie Mellon’s secure coding instance). They usually give a ranking on the remediation cost and the severity of the rule. There are also language-specific coding conventions, as is the case with Sun’s coding conventions for the Java programming language[3].

Rules can be checked at different levels: function, class, file, package, application. The information is aggregated to upper-level artefacts with ecological inference in mind[4]: as an example the number of violations is summed up while the rate of acquired practices (non-violated rules) is individually computed for each level of artefact.


Contents


SQuORE rules

SQuORE rules apply to C, C++ and Java code. The following families of rules are defined: fault tolerance (2 rules), analysability (7 rules), maturity (1 rule), stability (10 rules), changeability (12 rules) and testability (13 rules). The extensive list of checks is the following:

  • No Fallthrough
    • Mnemonic: R_NOFALLTHROUGH
    • Families: Reliability, Changeability
    • Description: There shall be no fall through the next case in a switch statement. It threatens analysability of code (one may not understand where execution goes through) and stability (one needs to modify existing code to add a feature). It is related to rules Cert MSC17-C, Cert MSC18-CPP, Cert MSC20-C and Misra-C (2004) 15-2.
  • Default case
    • Mnemonic: R_DEFAULT
    • Families: Changeability, Stability, Fault tolerance
    • Description: The final clause of a switch statement shall be the default clause. It is related to Cert MSC01-C, Cert MSC01-CPP and Misra-C (2004) rule 15.3.
  • Label out of a switch
    • Mnemonic: R_NOLABEL
    • Families: Reliability
    • Description: A switch label shall only be used when the most closely-enclosing compound statement is the body of a switch statement. It is related to Misra-C (2004) rule 15.1.
  • Use of continue
    • Mnemonic: R_NOCONT
    • Families: Analysability, Testability
    • Description: The 'continue' statement shall not be used. It is related to MISRA-C (2004) rule 14.5.
  • Multiple break
    • Mnemonic: R_SGLBRK
    • Families:
    • Description: or any iteration statement there shall be at most one break statement used for loop termination. It is related to Misra-C (2004) rule 14.6 and impacts the analysability (developers will have trouble understanding the control flow) and testability (more paths to test) of code.
  • No Goto
    • Mnemonic: R_NOGOTO
    • Families: Analysability, Changeability, Testability
    • Description: Gotos are considered bad practice (Misra-C (2004) rule 14.4) and may be hazardous (see CERT MSC35-CPP): they threaten the analysability of code, because one needs to scroll through the file instead of following a clear sequence of steps, and makes the test cases harder to write.
  • No Backward Goto
    • Mnemonic: R_BWGOTO
    • Families: Stability, Changeability, Testability
    • Description: This rule searches for goto operators that link to code that lies before the goto. Backward gotos shall not be used; they shall be rewritten using a loop instead.
  • No case in switch
    • Mnemonic: R_ONECASE
    • Families:
    • Description: Every switch statement shall have at least one case clause. It is releated to Misra-C (2004) rule 15.5.
  • Multiple exits
    • Mnemonic: R_RETURN
    • Families:
    • Description: A function shall have a single point of exit at the end. It is related to MISRA-C (2004) rule 14.7[5].
  • No final else
    • Mnemonic: R_ELSEFINAL
    • Families:
    • Description: All if ... else if constructs shall be terminated with an else clause. This impacts changeability, because developers can identify quickly what is the default treatment, and fault tolerance because unseen cases are caught. It is related to Misra-C (2004) rule 14.10.
  • Code before first case
    • Mnemonic: R_NOCODEBEFORECASE
    • Families:
    • Description: There shall be no code before the first case of a switch statement. It is related to Cert DCL41-C.
  • Assignment without Comparison
    • Mnemonic: R_NOASGCOND
    • Families: Stability, Testability
    • Description: Assignment operators shall not be used in expressions that do not contain comparison operators.
  • Missing Break
    • Mnemonic: R_BRKFINAL
    • Families:
    • Description: An unconditional break statement shall terminate every non-empty switch clause (see [MISRA-C:2004]: RULE 15.2).
  • Assignment in Boolean
    • Mnemonic: R_NOASGINBOOL
    • Families: Stability, Testability
    • Description: Assignment operators shall not be used in expressions that yield a boolean value. It is related to Cert EXP45-C, Cert EXP19-CPP and Misra-C (2004) rule 13.1.
  • No Compound If
    • Mnemonic: R_COMPOUNDIFELSE
    • Families:
    • Description: An if (expression) construct shall be followed by a compound statement. The else keyword shall be followed by either a compound statement, or another if statement. It is related to Misra-C (2004) rule 14.9.

Checkstyle rules

We identified 39 elements from the Checkstyle 5.6 rule set, corresponding to useful practices generally well adopted by the community. The quality attributes impacted by these rules are: analysability (23 rules), reusability (11 rules), reliability (5 rules), efficiency (5 rules), testability (3 rules), robustness (2 rules) and portability (1 rule). All rules are described on the project page at http://checkstyle.sourceforge.net/config.html .

Javadoc related checks ensure that Javadoc comments are present at the different levels of information as it is recommended by Sun[3].

  • Javadoc Method:
    • Mnemonic: JAVADOCMETHODCHECK
    • Families: Analysability
    • Description: Checks the Javadoc of a method or constructor. By default, does not check for unused throws. The scope to verify defaults to Scope.PRIVATE.
  • Javadoc Package:
    • Mnemonic: JAVADOCPACKAGECHECK
    • Families: Analysability
    • Description: Checks that each Java package has a Javadoc file used for commenting. By default it only allows a package-info.java file, but can be configured to allow a package.html file.
  • Javadoc Type:
    • Mnemonic: JAVADOCTYPECHECK
    • Families: Analysability
    • Description: Checks Javadoc comments for class and interface definitions. By default, does not check for author or version tags. The scope to verify defaults to Scope.PRIVATE.
  • Javadoc Variable:
    • Mnemonic: JAVADOCVARIABLECHECK
    • Families: Analysability
    • Description: A variable shall have a Javadoc comment.

Import related checks

  • Unused Imports:
    • Mnemonic: UNUSEDIMPORTSCHECK
    • Families: Analysability
    • Description: Looks for declared imports that are not used in the file. They clutter space and are misleading for readers.
  • Avoid Star Import:
    • Mnemonic: AVOIDSTARTIMPORTCHECK
    • Families: Stability
    • Description: Checks that no generic import is used; specific import statements shall be used to help the reader grasp what is inherited in the file.
  • Redundant Import:
    • Mnemonic: REDUNDANTIMPORTCHECK
    • Families: Reusability, Efficiency
    • Description: Checks for imports that are redundant.

Block related checks:

  • Empty Block:
    • Mnemonic: EMPTYBLOCKCHECK
    • Families: Reusability, Efficiency
    • Description: There shall be no empty blocks. They are useless and just add code, making it less readable.
  • Need Braces:
    • Mnemonic: NEEDBRACESCHECK
    • Families: Analysability
    • Description: braces shall surround code blocks.
  • Right Curly:
    • Mnemonic: RIGHTCURLYCHECK
    • Families: Analysability
    • Description: Right curly braces shall stand alone on a new line.

Others:

  • Visibility Modifier:
    • Mnemonic: VISIBILITYMODIFIERCHECK
    • Families: Testability
    • Description: The visibility of class members shall be explicitly specified.
  • Interface Is Type
    • Mnemonic: INTERFACEISTYPECHECK
    • Families: Changeability, Programming technics
    • Description: Use Interfaces only to define types - Implements Effective Java, Item 17[6].
  • Design For Extension
    • Mnemonic: DESIGNFOREXTENSIONCHECK
    • Families: Changeability, Reusability, Architecture
    • Description: Classes shall be designed for inheritance.
  • Avoid Inline Conditionals
    • Mnemonic: AVOIDINLINECONDITIONALSCHECK
    • Families: Analysability
    • Description: Inline conditionals shall not be used.
  • Empty Statement:
    • Mnemonic: EMPTYSTATEMENTCHECK
    • Families: Analysability, Efficiency
    • Description: There shall be no empty statements (standalone semi colon).
  • Equals Hashcode:
    • Mnemonic: EQUALSHASHCODECHECK
    • Families: Reusability, Reliability, Fault tolerance
    • Description: A class that overrides equals() shall also override hashCode(). A caller may use both methods without knowing that one of them has not been modified to fit the behaviour intended when modifying the other one (consistency in behaviour). It impacts reusability, reliability and fault tolerance.
  • Final Local Variable:
    • Mnemonic: FINALLOCALVARIABLECHECK
    • Families: Reusability, Reliability, Fault tolerance
    • Description: Ensures that local variables that never get their values changed are declared final.
  • Hidden Field:
    • Mnemonic: HIDDENFIELDCHECK
    • Families: Reusability, Reliability
    • Description: A local variable or a parameter shall not shadow a field that is defined in the same class.
  • Magic Number:
    • Mnemonic: MAGICNUMBERCHECK
    • Families: Changeability, Programming technics
    • Description: Hard coded constant or magic numbers shall not be used. Magic numbers are actual numbers like 27 that appear in the code that require the reader to figure out what 27 is being used for. One should consider using named constants for any number other than 0 and 1. Using meaningful names for constants instead of using magic numbers in the code makes the code self-documenting, reducing the need for trailing comments. This rule is related to programming technics and changeability.
  • Redundant Throws:
    • Mnemonic: REDUNDANTTHROWSCHECK
    • Families: Reusability, Efficiency
    • Description: There shall be no redundant exceptions declared in throws clause such as duplicates, unchecked exceptions or subclasses of another declared exception.
  • Simplify Boolean Return:
    • Mnemonic: SIMPLIFYBOOLEANRETURNCHECK
    • Families: Analysability
    • Description: There shall be no overly complicated boolean return statements.
  • String Literal Equality:
    • Mnemonic: STRINGLITERALEQUALITYCHECK
    • Families: Reusability, Reliability
    • Description: Checks that string literals are not used with == or !=. The rationale is novice Java programmers often use code like if (x == "something") when they mean if ("something".equals(x)).
  • Illegal Throws:
    • Mnemonic: ILLEGALTHROWSCHECK
    • Families: Reusability, Reliability, Fault tolerance
    • Description: Lists exceptions that are illegal or too generic; throwing java.lang.Error or java.lang.RuntimeException is considered to be almost never acceptable. In these
  • Parameter Assignment:
    • Mnemonic: PARAMETERASSIGNMENTCHECK
    • Families: Analysability
    • Description: Disallow assignment of parameters.
  • Multiple String Literals:
    • Mnemonic: MULTIPLESTRINGLITERALSCHECK
    • Families: Reusability, Efficiency
    • Description: Checks for multiple occurrences of the same string literal within a single file. It should be defined as a constant, both for reusability and changeability, so people can change the string at first sight without forgetting occurrences.
  • Multiple Variable Declarations:
    • Mnemonic: MULTIPLEVARIABLEDECLARATIONSCHECK
    • Families: Analysability
    • Description: Each variable declaration shall be in its own statement and on its own line.
  • Unnecessary Parentheses:
    • Mnemonic: UNNECESSARYPARENTHESESCHECK
    • Families: Analysability
    • Description: Checks if unnecessary parentheses are used in a statement or expression.
  • One Statement Per Line:
    • Mnemonic: ONESTATEMENTPERLINECHECK
    • Families: Analysability
    • Description: There shall be only one statement per line.
  • Class Data Abstraction Coupling:
    • Mnemonic: CLASSDATAABSTRACTIONCOUPLINGCHECK
    • Families: Testability
    • Description: Measures the number of instantiations of other classes within the given class.
  • Class Fanout Complexity:
    • Mnemonic: CLASSFANOUTCOMPLEXITYCHECK
    • Families: Testability
    • Description: The number of other classes a given class relies on.
  • Newline At End Of File:
    • Mnemonic: NEWLINEATENDOFFILECHECK
    • Families: Analysability
    • Description: Checks that there is a trailing newline at the end of each file. This is an ages-old convention, but many tools still complain when they find no trailing newline. Examples include diff or cat commands, and some SCM systems like CVS will print a warning when they encounter a file that does not end with a newline.
  • Translation:
    • Mnemonic: TRANSLATIONCHECK
    • Families: Reusability, Portability, Adaptability
    • Description: The Translation class helps to ensure the correct translation of code by checking property files for consistency regarding their keys.
  • Array Type Style:
    • Mnemonic: ARRAYTYPSTYLECHECK
    • Families: Analysability
    • Description: Array type definitions shall be Java style i.e. type[] variable.
  • Modifier Order:
    • Mnemonic: MODIFIERORDERCHECK
    • Families: Analysability
    • Description: The order of modifiers shall conform to the suggestions in the Java Language specification[7], sections 8.1.1, 8.3.1 and 8.4.3.
  • Redundant Modifier:
    • Mnemonic: REDUNDANTMODIFIERCHECK
    • Families: Reusability, Efficiency
    • Description: There shall be no redundant modifiers in interface and annotation definitions.
  • Line Length:
    • Mnemonic: LINELENGTHCHECK
    • Families: Analysability
    • Description: Lines shall not be too long (up to 100 columns).
  • Anon Inner Length:
    • Mnemonic: ANONINNERLENGTHCHECK
    • Families: Analysability
    • Description: Checks for long anonymous inner classes. For analysability reasons these should be defined as self-standing classes if they embed too much logic.
  • No White Space Before:
    • Mnemonic: NOWHITESPACEBEFORECHECK
    • Families: Analysability
    • Description: Checks that there is no whitespace before a token.
  • Package Name:
    • Mnemonic: PACKAGENAMECHECK
    • Families: Analysability
    • Description: Package names shall be named in lower case.

PMD Rules

We selected 58 rules from the PMD 5.0.5 rule set. These are related to the following quality attributes: analysability (26 rules), maturity (31 rules), testability (13 rules), changeability (5 rules), and efficiency (5 rules). The full rule set is documented on the PMD web site: http://pmd.sourceforge.net/pmd-5.0.5/rules/.

  • Jumbled incrementer:
    • Mnemonic: JUMBLEDINCREMENTER
    • Families: Maturity
    • Description: Detects when a variable used in a structure is modified in a nested structure. One shall avoid jumbled loop incrementers – it is usually a mistake, and even when it is intended it is confusing for the reader.
  • Return from finally block:
    • Mnemonic: RETURNFROMFINALLYBLOCK
    • Families: Maturity
    • Description: One shall avoid returning from a finally block since this can discard exceptions. This rule has an effect on analysability (developers will have trouble understanding where the exception comes from) and fault tolerance (the return method in the finally block may be stopping the exception that happened in the try block from propagating up even though it is not caught). It is related to the Cert ERR04-J rule.
  • Unconditional If Statement
    • Mnemonic: UNCONDITIONALIFSTATEMENT
    • Families: Analysability, Maturity
    • Description: Unconditional if statements are useless and clutter code. They impact analysability – developers will spend more time trying to understand what they are for, and they may have undesirable side effects.
  • Boolean Instantiation:
    • Mnemonic: BOOLEANINSTANTIATION
    • Families: Efficiency
    • Description: Avoid instantiating Boolean objects; you can reference Boolean.TRUE, Boolean.FALSE, or call Boolean.valueOf() instead.
  • Class Cast Exception With To Array:
    • Mnemonic: CLASSCASTEXCEPTIONWITHTOARRAY
    • Families: Maturity
    • Description: When deriving an array of a specific class from your Collection, one should provide an array of the same class as the parameter of the toArray() method. Doing otherwise you will will result in a ClassCastException.
  • Avoid Decimal Literals In Big Decimal Constructor:
    • Mnemonic: AVOIDDECIMALLITERALSINBIGDECIMALCONSTRUCTOR
    • Families: Maturity
    • Description: One might assume that the result of new BigDecimal(0.1) is exactly equal to 0.1, but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double (or as a binary fraction of any finite length). Thus, the long value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding. The (String) constructor, on the other hand, is perfectly predictable.
  • Misplaced Null Check:
    • Mnemonic: MISPLACEDNULLCHECK
    • Families: Maturity
    • Description: The null check here is misplaced. If the variable is null a NullPointerException will be thrown. Either the check is useless (the variable will never be null) or it is incorrect.
  • Avoid Thread Group:
    • Mnemonic: AVOIDTHREADGROUP
    • Families: Maturity
    • Description: Avoid using java.lang.ThreadGroup; although it is intended to be used in a threaded environment it contains methods that are not thread-safe.
  • Broken Null Check:
    • Mnemonic: BROKENNULLCHECK
    • Families: Maturity
    • Description: Detects cases where a null check is broken since it will throw a NullPointerException itself. It is likely that you used || instead of && or vice versa.
  • Avoid Using Hard Coded IP:
    • Mnemonic: AVOIDUSINGHARDCODEDIP
    • Families: Maturity
    • Description: Application with hard-coded IP addresses can become impossible to deploy in some cases. Externalizing IP addresses is preferable.
  • Too Many Fields:
    • Mnemonic: TOOMANYFIELDS
    • Families: Changeability
    • Description: Classes that have too many fields can become unwieldy and could be redesigned to have fewer fields, possibly through grouping related fields in new objects. For example, a class with individual city/state/zip fields could park them within a single Address field.
  • Excessive Parameter List:
    • Mnemonic: EXCESSIVEPARAMETERLIST
    • Families: Analysability, Changeability
    • Description: Methods with numerous parameters are a challenge to maintain, especially if most of them share the same data type. These situations usually denote the need for new objects to wrap the numerous parameters.
  • Excessive Public Count:
    • Mnemonic: EXCESSIVEPUBLICCOUNT
    • Families: Analysability
    • Description: Classes with large numbers of public methods and attributes require disproportionate testing efforts since combinational side effects grow rapidly and increase risk. Refactoring these classes into smaller ones not only increases testability and reliability but also allows new variations to be developed easily.
  • Coupling Between Objects:
    • Mnemonic: COUPLINGBETWEENOBJECTS
    • Families: Analysability, Testability
    • Description: This rule counts the number of unique attributes, local variables, and return types within an object. A number higher than the specified threshold can indicate a high degree of coupling.
  • Excessive Imports:
    • Mnemonic: EXCESSIVEIMPORTS
    • Families: Analysability, Testability
    • Description: A high number of imports can indicate a high degree of coupling within an object. This rule counts the number of unique imports and reports a violation if the count is above the default threshold.
  • Loose Coupling:
    • Mnemonic: LOOSECOUPLING
    • Families: Others
    • Description: Avoid using implementation types (i.e., HashSet); use the interface (i.e, Set) instead.
  • Non Thread Safe Singleton:
    • Mnemonic: NONTHREADSAFESINGLETON
    • Families: Maturity
    • Description: Non-thread safe singletons can result in bad, unpredictable state changes. Static singletons are usually not needed as only a single instance exists anyway: they can be eliminated by instantiating the object directly. Other possible fixes are to synchronize the entire method or to use an initialize-on-demand holder class. See Effective Java[8] item 48, and Cert MSC07-J.
  • Avoid Deeply Nested If Statements:
    • Mnemonic: AVOIDDEEPLYNESTEDIFSTMTS
    • Families: Analysability, Testability
    • Description: Avoid creating deeply nested if-then statements since they are harder to read and error-prone to maintain.
  • Switch Density:
    • Mnemonic: SWITCHDENSITY
    • Families: Analysability, Testability
    • Description: A high ratio of statements to labels in a switch statement implies that the switch statement is overloaded. Consider moving the statements into new methods or creating subclasses based on the switch variable.
  • Close Resource:
    • Mnemonic: CLOSERESOURCE
    • Families: Maturity
    • Description: Ensure that resources (like Connection, Statement, and ResultSet objects) are always closed after use.
  • Non Static Initializer:
    • Mnemonic: NONSTATICINITIALIZER
    • Families: Analysability, Testability
    • Description: A non-static initialiser block will be called any time a constructor is invoked (just prior to invoking the constructor). While this is a valid language construct, it is rarely used and is confusing.
  • Non Case Label In Switch Statement:
    • Mnemonic: NONCASELABELINSWITCHSTATEMENT
    • Families: Analysability, Testability
    • Description: A non-case label (e.g. a named break/continue label) was present in a switch statement.This legal, but confusing. It is easy to mix up the case labels and the non-case labels.
  • Bad Comparison:
    • Mnemonic: BADCOMPARISON
    • Families: Maturity
    • Description: Avoid equality comparisons with Double.NaN. Due to the implicit lack of representation precision when comparing floating point numbers these are likely to cause logic errors.
  • Confusing Ternary:
    • Mnemonic: CONFUSINGTERNARY
    • Families: Analysability, Testability
    • Description: 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, such as "does the error case go first?" or "does the common case go first?".
  • Assignment To Non Final Static:
    • Mnemonic: ASSIGNMENTTONONFINALSTATIC
    • Families: Maturity
    • Description: Identifies a possible unsafe usage of a static field.
  • Use Notify All Instead Of Notify:
    • Mnemonic: USENOTIFYALLINSTEADOFNOTIFY
    • Families: Maturity
    • Description: Thread.notify() awakens a thread monitoring the object. If more than one thread is monitoring, then only one is chosen. The thread chosen is arbitrary; thus its usually safer to call notifyAll() instead.
  • Simplify Conditional:
    • Mnemonic: SIMPLIFYCONDITIONAL
    • Families: Analysability, Testability
    • Description: No need to check for null before an instanceof; the instanceof keyword returns false when given a null argument.
  • Position Literals First In Comparisons:
    • Mnemonic: POSITIONLITERALSFIRSTINCOMPARISONS
    • Families: Maturity
    • Description: One should position literals first in comparisons because if the second argument is null then NullPointerExceptions can be avoided: they will just return false.
  • Preserve Stack Trace:
    • Mnemonic: PRESERVESTACKTRACE
    • Families: Maturity
    • Description: Throwing a new exception from a catch block without passing the original exception into the new exception will cause the original stack trace to be lost, making it difficult to debug effectively.
  • Return Empty Array Rather Than Null:
    • Mnemonic: RETURNEMPTYARRAYRATHERTHANNULL
    • Families: Maturity
    • Description: For any method that returns an array, it is a better to return an empty array rather than a null reference. This removes the need for null checking all results and avoids inadvertent NullPointerExceptions.
  • God Class:
    • Mnemonic: GODCLASS
    • Families: Maintainability, Analysability, Testability
    • Description: Detects the God Class design flaw using metrics. God classes do too many things, are very big and overly complex. They should be split apart to be more object-oriented. The rule uses the detection strategy described in Object-Oriented Metrics in Practice[9].
  • Empty Catch Block:
    • Mnemonic: EMPTYCATCHBLOCK
    • Families: Maintainability, Analysability
    • Description: Empty catch blocks are instances where an exception is caught, but nothing is done. In most circumstances an exception should either be acted on or reported, as examplified in the Cert ERR00-J rule.
  • Empty Try Block
    • Mnemonic: EMPTYTRYBLOCK
    • Families: Efficiency, Analysability
    • Description: Empty try blocks serve no purpose and should be remove because they clutter the file’s analysability. They also add useless runtime complexity.
  • Empty Finally Block:
    • Mnemonic: EMPTYFINALLYBLOCK
    • Families: Analysability, Maturity
    • Description: Empty finally block serve no purpose and should be remove because they clutter the file’s analysability. They also add useless runtime complexity.
  • Empty If Stmt:
    • Mnemonic: EMPTYIFSTMT
    • Families: Analysability, Maturity
    • Description: Empty If Statement finds instances where a condition is checked but nothing is done about it. Such instances serve no purpose and should be removed. They impact analysability – developers will spend more time trying to understand what they are for, and they may have undesirable side effects.
  • Empty Statement Not In Loop:
    • Mnemonic: EMPTYSTATEMENTNOTINLOOP
    • Families: Analysability, Maturity
    • Description: An empty statement (or a semicolon by itself) that is not used as the sole body of a 'for' or 'while' loop is probably a bug. It could also be a double semicolon, which has no purpose and should be removed.
  • Empty Switch Statements:
    • Mnemonic: EMPTYSWITCHSTATEMENTS
    • Families: Analysability, Maturity
    • Description: Empty switch statements serve no purpose and should be removed. They impact analysability – developers will spend more time trying to understand what they are for, and they may have undesirable side effects.
  • Empty Synchronized Block:
    • Mnemonic: EMPTYSYNCHRONIZEDBLOCK
    • Families: Analysability, Maturity
    • Description: Empty synchronized blocks serve no purpose and should be removed. They impact analysability – developers will spend more time trying to understand what they are for, and they may have undesirable side effects.
  • Empty While Statement:
    • Mnemonic: EMPTYWHILESTMT
    • Families: Analysability, Maturity
    • Description: Finds all instances where a while statement does nothing. Empty while statements are useless and clutter code. They impact analysability – developers will spend more time trying to understand what they are for, and they may have undesirable side effects. If it is a timing loop then Thread.sleep() is better suited; if it does a lot in the exit expression then it should be rewritten to make it clearer. All these are related to Cert MSC12-C.
  • Duplicate Imports:
    • Mnemonic: DUPLICATEIMPORTS
    • Families: Analysability, Testability
    • Description: Duplicate or overlapping import statements should be avoided.
  • Dont Import Java Lang:
    • Mnemonic: DONTIMPORTJAVALANG
    • Families: Analysability, Testability
    • Description: Avoid importing anything from the package 'java.lang'. These classes are automatically imported (JLS 7.5.3[10]).
  • Import From Same Package:
    • Mnemonic: IMPORTFROMSAMEPACKAGE
    • Families: Analysability, Changeability
    • Description: There is no need to import a type that lives in the same package.
  • Too Many Static Imports:
    • Mnemonic: TOOMANYSTATICIMPORTS
    • Families: Changeability
    • Description: If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all the static members you import. Readers of your code (including you, a few months after you wrote it) will not know which class a static member comes from (see Sun 1.5 Language Guide[7]).
  • System Println:
    • Mnemonic: SYSTEMPRINTLN
    • Families: Others
    • Description: References to System.(out|err).print are usually intended for debugging purposes and can remain in the codebase even in production code. By using a logger one can enable/disable this behaviour at will (and by priority) and avoid clogging the Standard out log.
  • Method With Same Name As Enclosing Class:
    • Mnemonic: METHODWITHSAMENAMEASENCLOSINGCLASS
    • Families: Analysability, Maturity
    • Description: Non-constructor methods should not have the same name as the enclosing class.
  • Avoid Catching NPE:
    • Mnemonic: AVOIDCATCHINGNPE
    • Families: Maturity
    • Description: Code should never throw NullPointerExceptions under normal circumstances. A catch block for such an exception may hide the original error, causing other, more subtle problems later on. It is related to the Cert ERR08-J rule.
  • Avoid Catching Throwable:
    • Mnemonic: AVOIDCATCHINGTHROWABLE
    • Families: Maturity
    • Description: Catching Throwable errors is not recommended since its scope is very broad. It includes runtime issues such as OutOfMemoryError that should be exposed and managed separately. It is related to the CERT ERR07-J rule.
  • Avoid Throwing NullPointerException:
    • Mnemonic: AVOIDTHROWINGNULLPOINTEREXCEPTION
    • Families: Analysability, Testability
    • Description: Avoid throwing NullPointerExceptions. These are confusing because most people will assume that the virtual machine threw it. Consider using an IllegalArgumentException instead; this will be clearly seen as a programmer-initiated exception.
  • Avoid Throwing Raw Exception Types:
    • Mnemonic: AVOIDTHROWINGRAWEXCEPTIONTYPES
    • Families: Analysability, Testability
    • Description: Avoid throwing certain exception types. Rather than throw a raw RuntimeException, Throwable, Exception, or Error, use a subclassed exception or error instead.
  • Avoid Rethrowing Exception:
    • Mnemonic: AVOIDRETHROWINGEXCEPTION
    • Families: Analysability, Changeability, Efficiency
    • Description: Catch blocks that merely rethrow a caught exception only add to code size and runtime complexity.
  • Do Not Throw Exception In Finally:
    • Mnemonic: DONOTTHROWEXCEPTIONINFINALLY
    • Families: Maturity
    • Description: Throwing exceptions within a 'finally' block is confusing since they may mask other exceptions or code defects. Similar to Lint4J's Throw in a finally block rule.
  • Unnecessary Case Change:
    • Mnemonic: UNNECESSARYCASECHANGE
    • Families: Efficiency
    • Description: Using equalsIgnoreCase() is faster than using toUpperCase/toLowerCase().equals().
  • UseStringBufferLength:
    • Mnemonic: USESTRINGBUFFERLENGTH
    • Families: Efficiency
    • Description: Use StringBuffer.length() to determine StringBuffer length rather than using StringBuffer.toString().equals or StringBuffer.toString().length().
  • Method Returns Internal Array:
    • Mnemonic: METHODRETURNSINTERNALARRAY
    • Families: Maturity
    • Description: Exposing internal arrays to the caller violates object encapsulation since elements can be removed or replaced outside of the object that owns it. It is safer to return a copy of the array.
  • Array Is Stored Directly:
    • Mnemonic: ARRAYISSTOREDDIRECTLY
    • Families: Maturity
    • Description: Constructors and methods receiving arrays should clone objects and store the copy.This prevents future changes from the user from affecting the original array.
  • Unused Private Method:
    • Mnemonic: UNUSEDPRIVATEMETHOD
    • Families: Maturity
    • Description: Unused Private Method detects when a private method is declared but is unused.
  • Unused Local Variable:
    • Mnemonic: UNUSEDLOCALVARIABLE
    • Families: Maturity
    • Description: Detects when a local variable is declared and/or assigned, but not used.
  • Unused Private Field:
    • Mnemonic: UNUSEDPRIVATEFIELD
    • Families: Efficiency
    • Description: Detects when a private field is declared and/or assigned a value, but not used.

References

  1. See the official MISRA web site at http://www.misra.org.uk/.
  2. See Carnegie Mellon’s web site: https://www.securecoding.cert.org.
  3. 3.0 3.1 Sun. (1999). Code Conventions for the Java Programming Language.
  4. Posnett, D., Filkov, V., & Devanbu, P. (2011). Ecological inference in empirical software engineering. In Proceedings of the 2011 26th IEEE/ACM International Conference on Automated Software Engineering (pp. 362–371). IEEE Computer Society. doi:10.1109/ASE.2011.6100074
  5. See C2's wiki for useful comments on this law: http://c2.com/cgi/wiki?SingleFunctionExitPoint .
  6. Bloch, J. (2008). Effective Java (2nd Edition). Addison-Wesley.
  7. 7.0 7.1 Sun. (2005). Sun 1.5 Java Language Guide.
  8. Bloch, J. (2008). Effective Java (2nd Edition). Addison-Wesley. Retrieved from http://www.amazon.com/Effective-Java-Edition-Joshua-Bloch/dp/0321356683
  9. Lanza, M., & Marinescu, R. (2006). Object-oriented metrics in practice: using software metrics to characterize, evaluate, and improve the design of object-oriented systems. (Springer, Ed.).
  10. Gosling, J., Joy, B., Steele, G., Bracha, G., & Buckley, A. (2013). Java Language Specification. Retrieved from http://docs.oracle.com/javase/specs/jls/se7/html/index.html
Personal tools