New JSHint Features
Many of you are aware of the JSHint code quality tool that has been around for the past couple of years. As of recently, the following new options that have been added regarding the complexity of a function.
Parameters, Depth, and Statements
By reducing the number of parameters, the number of nesting, and the number of statements in your function you can dramatically increate the readability and modularity of your code.
The following piece of code shows using the
maxstatementsto warn us of possible issue with our functions.
JSHint gives an error that too many parameters were used because we limited
maxparamsto 3 and the code accepted 4 parameters. An error occurred because the depth of logic is too deep because we limited it to a
maxdepthof 2. We will also get an error about the number of lines in our function because we limited
maxstatementsto 5 and we have many more than that.
A less commonly known software metric used to evaluate functions is Cyclomatic Complexity. Like it sounds, it's purpose is to calculate the overall intricacy of a function and to give a score that reflects it's complexity.
"The cyclomatic complexity of a section of source code is the count of the number of linearly independent paths through the source code." --http://en.wikipedia.org/wiki/Cyclomatic_complexity
In addition to the above parameters, depth, and statement metrics you can now track the overall complexity using the
As you see above, the above function has more complexity that what we set in
You might be wondering what a reasonable
maxcomplexityvalue is for your project. In the 2nd edition of Steve McConnell's Code Complete he recommends that a cyclomatic complexity from 0 to 5 is typically fine, but you should be aware if the complexity starts to get in the 6 to 10 range. He further explains that anything over a complexity of 10 you should strongly consider refactoring your code.
.jshintrcfile in your project and JSHint should pick up those settings. This is handy if your project is large and you want some consistent settings across the board.