Skip to content

On JavaScript Complexity

Limiting complexity is a noble goal in engineering.

By limiting complexity, we make our code easier to understand and maintain for future developers on the project. To be honest, you make it easier for yourself to understand in the future as well.

Code complexity is something we discuss at Code Retreat (Philadelphia), and recently, a neat looking grunt plugin came out allowing you to monitor your complexity as part of your grunt process. It reminds me of a great service that was recently released for the Ruby community, called Code Climate, which monitors complexity and other measures.

Let’s take some time do discuss what we mean by ‘complex code.’

How do we define complex code?

Complexity can be very simple to define, or very mathematically complicated (ironically?).

At Code Retreat (Philadelphia), we say that if your methods are over 5 lines long, they’re too complex. It’s a very low margin, but if you’re just getting started in terms of thinking about complexity, it could be a good place to challenge yourself.

That kind of simple complexity rule is called “Lines of Code” (clever, yeah?) or LOC if you see it abbreviated.

Other measures of complexity

Cyclomatic complexity computes a measure of complexity based on a control flow graph:


From ye olde Wikipedia

The name refers to the number of cycles found in this control flow, not cycles found in the code. Lower is generally better. For more information, the wikipedia article is well maintained.

Other mathematical measures of complexity include the Halstead measures, developed when Maurice Halstead encouraged a more empirical and scientific approach to software development in the late 70s. The measures encompass more than complexity, but some of the metrics included are number of distinct operators, number of distinct operands, and the totals of each. These numbers are then formulated into program vocabulary, program length, volume, difficult, effort and more. They are covered in some detail here.

Summary

It seems to me that as there is a greater interest in code craftsmanship and maintaining code quality, it makes sense for the discussion of complexity to resurface. From simple measures such as lines of code to mathematical calculations like cyclomatic complexity and the Halstead measures, we have a means to study our code’s complexity.

For another article on JavaScript complexity, check out jscomplexity.org. While I was inspired to look more deeply into this topic from a Grunt plugin, JSComplexity is a copy/paste analysis website, leveraging another npm package, complexity-report, which is well worth looking into.

UPDATE: A friend sent me a link to a very interesting looking video that’s another take on code complexity.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.