Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Codenarc Revisited - Gr8Conf EU 2016

Codenarc Revisited - Gr8Conf EU 2016

Codenarc Revisited
------------
When was the last time you looked at code quality? Do you have some old codenarc configuration with half(or more!) of the rules turned off because they were reporting false positives? Or maybe you have @SupressWarnings all over your code? Or perhaps you want to do something small like to enforce tabs vs spaces for all members of your team?

Codenarc is a static analysis tool for Groovy that enforces style, detects bad practices, and suggests improvements. If it has been awhile since you last looked at codenarc, there might be new rules or configuration options to get you back on the path to better code quality. This session will explore what is new with codenarc, options for specific groovy ecosystem projects such as grails, and walk through how to create custom rules for your own project.
------------
Jennifer “Jenn” Strater is a software engineer with a passion for developing and designing applications using new and innovative technologies. Her strengths are in the service layer including building RESTful APIs. Jenn also has experience with relational and NoSQL databases, devops, front-end, and mobile in the healthcare and transportation industries. She learns new tools and systems quickly and introduces new technology learned through local community groups, involvement in the international Groovy community, and when speaking at or attending regional, national, and international conferences.

Jenn is the co-founder of the organization Gr8Ladies and has organized Gr8Workshops for developers interested in an overview and crash course in Groovy technologies. She has presented at various Minnesota tech events, the Grace Hopper Celebration of Women in Computing, Greach, Gr8Conf EU, Gr8Conf US, and Devoxx Belgium.

Starting in September, Jenn will be a master's student at the Technical University of Denmark studying static analysis and compilers with a focus on Groovy with funding from the Fulbright U.S. student program.

jlstrater

June 03, 2016
Tweet

More Decks by jlstrater

Other Decks in Technology

Transcript

  1. Codenarc Revisited
    Jenn Strater
    @codeJENNerator

    View full-size slide

  2. Follow Along
    • https://github.com/jlstrater/gr8data/tree/master/config/codenarc
    • https://github.com/jlstrater/groovy-spring-boot-restdocs-
    example/tree/master/gradle/codenarc

    View full-size slide

  3. About Me
    • Senior Consultant at Object
    Partners, Inc.

    View full-size slide

  4. About Me
    • Senior Consultant at Object
    Partners, Inc.
    • Co-Founder of Gr8Ladies

    View full-size slide

  5. About Me
    • Senior Consultant at Object
    Partners, Inc.
    • Co-Founder of Gr8Ladies
    • 2016 - 2017 Fulbright US
    Student Program Selectee to
    Denmark

    View full-size slide

  6. Background
    • Spring Boot with Groovy

    View full-size slide

  7. Background
    • Spring Boot with Groovy
    • Ratpack with Groovy

    View full-size slide

  8. Background
    • Spring Boot with Groovy
    • Ratpack with Groovy
    • Grails

    View full-size slide

  9. Background
    • Spring Boot with Groovy
    • Ratpack with Groovy
    • Grails
    • Anything Else?

    View full-size slide

  10. https://github.com/CodeNarc/CodeNarc
    “CodeNarc is a static analysis tool for Groovy
    source code, enabling monitoring and
    enforcement of many coding standards and best
    practices…
    CodeNarc is similar to popular static analysis
    tools such as PMD or Checkstyle. Unlike those
    tools which analyze Java code, CodeNarc
    analyzes Groovy code.”

    View full-size slide

  11. • Website
    • codenarc.sourceforge.net

    View full-size slide

  12. • Website
    • codenarc.sourceforge.net
    • Current Version
    • 0.25.2

    View full-size slide

  13. • Mailing List
    • https://sourceforge.net/p/codenarc/mailman

    View full-size slide

  14. • Mailing List
    • https://sourceforge.net/p/codenarc/mailman
    • Project Admin
    • Chris Mair

    View full-size slide

  15. Why use Codenarc?
    • Improves readability
    • Saves time with code reviews
    • Code with fewer bugs
    • Help onboard new team members

    View full-size slide

  16. .equals instead of ==

    View full-size slide

  17. def someMethod(def something, def somethingElse) {

    if (something) {

    doSomething()

    }

    else if(somethingElse) {

    doSomethingElse()

    }

    }

    View full-size slide

  18. def someMethod(def something, def somethingElse) {

    if (something) {

    doSomething()

    }

    else if(somethingElse) {

    doSomethingElse()

    }

    }

    View full-size slide

  19. def someMethod(def something, def somethingElse) {

    if (something) {

    doSomething()

    }

    else if(somethingElse) {

    doSomethingElse()

    }

    }

    View full-size slide

  20. println “This is an unnecessary Groovy String”


    View full-size slide

  21. this.something.getThisThing()

    View full-size slide

  22. New Team Member

    View full-size slide

  23. if(true) { }
    vs
    if (true) { }
    vs
    if (ready){ }

    View full-size slide

  24. Leaning Tower of Code
    https://flic.kr/p/de4pmb

    View full-size slide

  25. Summary
    • Useful For:
    • Interns/Junior Devs
    • Java Devs converting to Groovy
    • New Team Members
    • YOU!

    View full-size slide

  26. Approaches
    • Start with one project or team
    • Turn on all rules
    • Look at all of the violations
    • Turn off rules that don’t make sense for your team
    • Fix all the problems
    • Once you have a good set of rules with minimal false
    positives, set that as the standard for all teams using
    Groovy

    View full-size slide

  27. Approaches
    • Turn on all the rules
    • Set a violation limit and fail builds that add go
    above the limit

    View full-size slide

  28. Basics
    https://flic.kr/p/oiAEx6

    View full-size slide

  29. What is a rule?

    View full-size slide

  30. What is a rule?
    MissingBlankLineAfterPackage

    View full-size slide

  31. What is a rule?
    MissingBlankLineAfterPackage
    package org.codenarc

    import java.util.Date // violation


    class MyClass {

    void go() { /* ... */ }

    }

    View full-size slide

  32. What is a ruleset?

    View full-size slide

  33. What is a ruleset?
    Formatting Rules ("rulesets/formatting.xml")

    View full-size slide

  34. Rule Configuration

    View full-size slide

  35. Rule Configuration
    • Priority

    View full-size slide

  36. Rule Configuration
    • Priority
    • ViolationMessage

    View full-size slide

  37. Rule Configuration
    • Priority
    • ViolationMessage
    • Description

    View full-size slide

  38. Rule Configuration
    • Priority
    • ViolationMessage
    • Description
    • Name

    View full-size slide

  39. Rule Configuration

    View full-size slide

  40. Rule Configuration
    • Parameters

    View full-size slide

  41. Rule Configuration
    • Parameters
    • applyToClassNames

    View full-size slide

  42. Rule Configuration
    • Parameters
    • applyToClassNames
    • applyToFileNames

    View full-size slide

  43. • runs with gradle check
    https://docs.gradle.org/current/userguide/codenarc_plugin.html

    View full-size slide

  44. Config Options

    View full-size slide

  45. Config Options
    • configFile
    • ignoreFailures
    • maxPriority1Violations
    • maxPriority2Violations
    • maxPriority3Violations

    View full-size slide

  46. Config Options

    View full-size slide

  47. Config Options
    • reportFormat
    • reportsDir
    • sourceSets
    • toolVersion

    View full-size slide

  48. codenarc {

    toolVersion = '0.25.2'

    }


    codenarcMain {

    configFile file('config/codenarc/codenarc.groovy')

    }


    codenarcTest {

    configFile file('config/codenarc/codenarcTest.groovy')

    }

    View full-size slide

  49. Starter Ruleset
    http://codenarc.sourceforge.net/StarterRuleSet-
    AllRulesByCategory.groovy.txt
    https://flic.kr/p/c8QjRC

    View full-size slide

  50. config/codenarc/codenarc.groovy
    ruleset {

    // rulesets/basic.xml

    AssertWithinFinallyBlock

    AssignmentInConditional

    BigDecimalInstantiation

    BitwiseOperatorInConditional

    BooleanGetBoolean

    BrokenNullCheck

    BrokenOddnessCheck

    ClassForName

    ComparisonOfTwoConstants

    ComparisonWithSelf

    ConstantAssertExpression

    ConstantIfExpression

    ConstantTernaryExpression

    .
    .
    .
    // rulesets/braces.xml

    ElseBlockBraces(bracesRequiredForElseIf: true)

    ForStatementBraces

    IfStatementBraces

    WhileStatementBraces
    .
    .
    .
    }

    View full-size slide

  51. Turning Off Rules - Comments
    ruleset {
    /*
    // rulesets/braces.xml

    ElseBlockBraces(bracesRequiredForElseIf: true)

    ForStatementBraces

    IfStatementBraces

    WhileStatementBraces
    */
    }

    View full-size slide

  52. Turning Off Rules -
    Enabled:False
    ruleset {
    ruleset('rulesets/basic.xml') {
    CatchThrowable(enabled:false)
    }
    }

    View full-size slide

  53. Suppress Warnings


    @SuppressWarnings('DuplicateStringLiteral')

    class MyClass {

    def y = 'x'

    def z = 'x'


    @SuppressWarnings(['IfStatementBraces', 'ThrowException'])

    int getCount() {

    if (!ready) throw new Exception('Not ready')

    }

    }

    View full-size slide

  54. https://flic.kr/p/rmit9T

    View full-size slide

  55. 0.21
    • No Wildcard Imports
    • Lots of New Formatting Rules
    • Consecutive Blank Lines
    • Blank Line Before Package
    • FileEndsWithoutNewline

    View full-size slide

  56. 0.22
    • No Def
    • Unnecessary Safe Navigation Operator

    View full-size slide

  57. 0.23
    • Nested For Loop

    View full-size slide

  58. 0.25
    • No Tab Character
    • Trailing Comma

    View full-size slide

  59. Each Release Improves Existing Rules
    https://flic.kr/p/3mPXcD

    View full-size slide

  60. Rules Worth Talking
    About

    View full-size slide

  61. File Ends Without
    NewLine

    View full-size slide

  62. I don’t like all of the Codenarc Rules!
    img src: https://flic.kr/p/rehEf5

    View full-size slide

  63. Dry
    • DuplicateListLiteral
    • DuplicateMapLiteral
    • DuplicateNumberLiteral
    • DuplicateStringLiteral

    View full-size slide

  64. Could Be Elvis
    Lots of false positives

    View full-size slide

  65. JUnit Ruleset
    Doesn’t work well with Spock

    View full-size slide

  66. No Def
    https://flic.kr/p/apRkJh

    View full-size slide

  67. No Def
    • Great for Spring Boot
    https://flic.kr/p/apRkJh

    View full-size slide

  68. No Def
    • Great for Spring Boot
    • Problematic with Grails
    https://flic.kr/p/apRkJh

    View full-size slide

  69. Good in Theory

    View full-size slide

  70. Good in Theory
    • Unnecessary Return

    View full-size slide

  71. Good in Theory
    • Unnecessary Return
    • Line Length

    View full-size slide

  72. Debatable
    • Unnecessary Groovy String

    View full-size slide

  73. Debatable
    • Unnecessary Groovy String
    • Unnecessary Getter

    View full-size slide

  74. Debatable
    • Misordered Static Imports

    View full-size slide

  75. Debatable
    • Misordered Static Imports
    • No Wildcard Imports

    View full-size slide

  76. Still Deciding

    View full-size slide

  77. Still Deciding
    • Complexity Metrics

    View full-size slide

  78. WARNING!
    • Enhanced Ruleset does not work with the gradle
    codenarc plugin
    • https://objectpartners.com/2016/03/16/resolving-
    codenarc-compilation-warnings/

    View full-size slide

  79. build/reports/codenarc/main.html

    View full-size slide

  80. Create a Custom Rule
    import org.codenarc.rule.AbstractRule

    import org.codenarc.source.SourceCode


    /**

    * Sample rule. Checks for static fields.

    */

    class MyStaticFieldRule extends AbstractRule {

    String name = 'MyStaticField'

    int priority = 2


    void applyTo(SourceCode sourceCode, List violations) {

    sourceCode.ast.classes.each { clazz ->

    clazz.fields.each { fieldNode ->

    if (fieldNode.static) {

    violations << createViolation(sourceCode, fieldNode)

    }

    }

    }

    }

    }

    View full-size slide

  81. Contribute
    • http://codenarc.sourceforge.net/codenarc-
    developer-guide.html
    • https://github.com/CodeNarc/CodeNarc

    View full-size slide

  82. Read the docs for more on..
    • Rule Specifics
    • Ant Task
    • Command Line

    View full-size slide

  83. Example Rulesets
    • Grails
    • https://github.com/jlstrater/gr8data/tree/master/
    config/codenarc
    • Spring Boot
    • https://github.com/jlstrater/groovy-spring-boot-
    restdocs-example/tree/master/gradle/codenarc

    View full-size slide

  84. Questions?
    https://flic.kr/p/5DeuzB

    View full-size slide