Grails Clean Code – Configure Codenarc Plugin
Grails gives us the freedom to create web applications quickly and with maximum productivity, but with the fast development, we often leave the basic code quality rules and after a few months of project we end up so much messy code that even we are not able to read it, forget about understanding it.
Codenarc really helps to identify what is not expected from our code. We can setup the codenarc plugin easily, but the default rulesets of plugins are sometimes not useful so download the default rulesets and save the file in grails-app/conf/CodeNarcRules.groovy and then configure the plugin by adding following code in BuildConfig.groovy.
[code]
codenarc{
ruleSetFiles = "file:grails-app/conf/CodeNarcRules.groovy" // Ruleset file path
reports = {
HtmlReport(‘html’) { // Report type is ‘html’
outputFile = ‘target/CodeNarcReport.html’ //Output file name
title = ‘My Test Code Narc Report’ // Title of the file
}
}
}
[/code]
After running the grails conarc command you will see some of the rules doesn’t fit to Grails infrastructure, so we can just ignore them and update some rules in our CodeNarcRules.groovy file which can make our code quality bit better e.g; the following changes
[code]
EmptyMethod{
doNotApplyToClassNames = "*Controller"
}
GrailsPublicControllerMethod{
enabled = false
}
MethodSize {
maxLines = 7
applyToClassNames = ‘*Controller’
}
MethodSize {
maxLines = 12
doNotApplyToClassNames = ‘*Controller’
}
[/code]
We can supress some warning on specific methods as well by just adding an annotation
[code]
@SuppressWarnings([‘MethodSize’, ‘LineLength’])
def someMethod(){
//Code
}
[/code]
We can also integrate it with our build system so that if the code doesn’t pass the minimum criteria the build gets failed by updating your configurations in BuildConfig.groovy
[code]
codenarc{
ruleSetFiles = "file:grails-app/conf/CodeNarcRules.groovy"
maxPriority1Violations = 3
systemExitOnBuildException = true
reports = {
HtmlReport(‘html’) { // Report type is ‘html’
outputFile = ‘target/CodeNarcReport.html’
title = ‘My Test Code Narc Report’
}
}
}
[/code]
It always good to have tool which can show you your mistakes and guide you write more readable and maintainable code. Because of this plugin I was able to delete hunderds of lines of unused code in my project.
Hope it helps
Thank you for sharing this valuable information. This helps a lot. 🙂
Nice. This helps.