Font Awesome Free 5.13.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)
Skip to main content

Static analysis

Checking your code without running it

Basic idea

Static analysis = checking codebase by looking at the source code without running it

Great addition to automated testing and code reviews

Formatting and coding style

  • Automated checking of formatting rules
  • Automated formatting
    • Example (multi-language): Prettier
    • Example (Java): Eclipse Code Formatter
  • Automated coding style checks

Common bugs and code smells

Technical debt and duplication

Note: stay practical about this!

  • The technical debt reported by tools like this is just an indication. Set your own priorities and see where the cost of paying off the debt is worth the benefits.
  • Not all duplication is bad duplication. See also Duplication.

Third-party dependencies

  • Check if third-party dependencies used by the code are properly defined
    • Example (JavaScript): dependency-cruiser (check for dependencies missing in package.json, production code relying on devDependencies or optionalDependencies, ...)
  • Check for known vulnerabilities in third-party dependencies
  • Check licenses for third-party dependencies

Internal dependencies

Example dependency-cruiser rule for enforcing custom boundary:

{
name: 'component-a',
severity: 'error',
comment: 'Do not reach into component A',
from: {
pathNot: '^src/componentA/'
},
to: {
path: '^src/componentA/',
pathNot: '^src/componentA/index',
}
}

Example automated test code for circular dependency checking with JDepend:

Collection packages = jdepend.analyze();
assertEquals("Cycles found", false, jdepend.containsCycles());

Example automated test code for checking direction of imports using JDepend:

DependencyConstraint constraint = new DependencyConstraint();
JavaPackage ejb = constraint.addPackage("com.xyz.ejb");
JavaPackage web = constraint.addPackage("com.xyz.web");
JavaPackage util = constraint.addPackage("com.xyz.util");

ejb.dependsUpon(util);
web.dependsUpon(util);

jdepend.analyze();
assertEquals("Dependency mismatch", true, jdepend.dependencyMatch(constraint));

Type checking

  • A programming language's type system can be seen as a form of static analysis
  • It's possible to add type checking to a language that doesn't have it built in
    • Example: using TypeScript to add type checking to a JavaScript codebase

Resources