Logo dévoreur 2 code

Tests and Code Quality - Come On, Let's Roll Up Our Sleeves and Refactor

Written by Fabien SchlegelFabien Schlegel
published 9/15/20194 min

It’s the beginning of the end

Sooner or later, it will happen: you’ll have to go back into old code, say from (put whatever date you like, it doesn’t matter).

And then, disaster strikes, everything falls apart. No comments, the variables are a’s, b’s, ifMyAuntHadOnes, and 80-line functions with if/else everywhere. In short, the guy in charge of reviewing the code before the merge, aka Super Lead Dev, was on vacation…

When we’re writing code and reach a working solution, we’re happy, we lift our hands off the keyboard, we commit, and we move on to the next thing.

Working this way, we produce crappy code and, above all, technical debt.

Technical debt is when we add elements to a project (code, dependencies, libraries, frameworks, etc.) that make it more complex, harder to maintain, and generate extra hours of work.

Who do we say thank you to

To improve code quality without crying every five minutes to the most experienced people on the team, we’re going to use a tool that analyzes our code.

As for me, I use Code Climate. It’s not the only one, but it’s free for public Github projects and easy to set up locally with docker for other projects.

The web version attached to public Github projects is more complete, with the portal analyzing the data found by the engines.

The basics

Code Climate shows an overall maintainability for the project in the code tab, a score per file with a letter from A to F, and a time to refactor the file.

Churn versus maintainability

churn versus maintainability

The idea is simple: the more often a file changes, the harder it is to maintain. This graph lets you track that information.

Technical debt

technical debt graph

Here we find a graph showing the percentage of technical debt as well as the time needed to refactor the code.

The problems begin

For each file, we get plenty of information about the issues found.

Cognitive complexity

Cognitive complexity measures how hard a piece of code is to read and understand.

Typically, nesting code in several layers containing loops, conditions and try/except (Python, or try/catch in JS) makes a function harder to understand.

The same goes for anything that breaks the flow of a function. The same culprits as for nesting, plus switch/case, combinations of logical operators, etc.

if (
  date !== "" &&
  endDate !== "" &&
  (date !== prevProps.date ||
    time !== prevProps.time ||
    endDate !== prevProps.endDate ||
    endTime !== prevProps.endTime)
) {
  if (moment(`${date} ${time}`).isBefore(moment(`${endDate} ${endTime}`))) {
    this.toggleButton(true);
    onTA(
      "danger",
      "La date de fin du vote ne peut pas être supérieure à la date de l'événement",
    );
    setTimeout(() => {
      offTA();
    }, 5000);
  } else if (moment(date).isBefore(moment(), "day")) {
    onTA(
      "warning",
      "Ca c'était avant, un peu tard pour programmer événement ;-) !",
    );
    setTimeout(() => {
      offTA();
    }, 5000);
  } else if (
    endDate !== "" &&
    endTime !== "" &&
    moment(`${endDate} ${endTime}`).isBefore(moment())
  ) {
    onTA(
      "warning",
      "Ca va être compliqué de voter, la fin du vote est passée !",
    );
    setTimeout(() => {
      offTA();
    }, 5000);
  } else if (disabledButton === true) {
    this.toggleButton(false);
  }
}

An example of a piece of code to refactor…

Cyclomatic complexity

Cyclomatic complexity, or McCabe’s measure, indicates the number of paths or decisions an algorithm can follow in a computer program.

For Python, we use Radon, which applies a penalty to each branch in the function. If we go over a threshold set in advance, the function is flagged as too complex and needs reworking.

It’s still different from cognitive complexity, even though the two are related.

Code duplication

This one is fairly self-explanatory: if two pieces of code are too similar, the engine considers it duplication. All that’s left is to extract it into a function to remove the duplicate!

And locally, it’s the same

As said at the beginning, the appeal of Code Climate is that they provide an open source version of their engine that we can use locally or in continuous integration.

We configure it with a nice YAML file.

version: 2

checks:
  identical-code:
    config:
      threshold: 25
  similar-code:
    config:
      threshold: 50

plugins:
  duplication:
    enabled: true
    debug: true
    config:
      languages:
        - python
        - javascript
  fixme:
    enabled: true
  radon:
    enabled: true
  sonar-python:
    enabled: true
  pep8:
    enabled: true
  eslint:
    enabled: true

exclude_patterns:
  - "htmlcov/"
  - "*/migrations/"
  - "*/tests/"

I’ll spare you the explanation of the thing, but if you’re interested, head over to the documentation.

Next is the command to run the engine locally. After fetching the containers for the tool and the engines with a docker pull, we run the command.

The chevron at the end means, on Linux, that we write the result to the cc_report.html file.

docker run   --interactive --tty --rm   --env CODECLIMATE_CODE="$PWD"
--volume "$PWD":/code   --volume /var/run/docker.sock:/var/run/docker.sock
--volume /tmp/cc:/tmp/cc codeclimate/codeclimate analyze -f html > cc_report.html

It’s the end of the end

And there you go, that’s all for today. See you next week for the next and final part of our series.


Share the post

Table of contents