In Episode 193 we covered the code linting tool Dogma. Dogma aims to strictly enforce a particular set of rules. Credo is a similar tool, but it's focused on giving gentle suggestions rather than strict enforcement. As a result, it's also going to find more issues with your code. You don't need to fix them all, but it gives good suggestions on things you might want to address. Let's have a look.

Project

We're going to run this on ElixirFriends. First thing's first, we pull it in as a dependency.

vim mix.exs
    {:credo, "~> 0.2", only: [:dev, :test]}

Fetch it:

mix deps.get

Now we're ready to run it:

mix credo

By default it just shows you a few things you could fix. If you want to see the entire list of issues Credo found, you can add a -a to it:

mix credo -a

The next feature is really sweet. It's called explain - you basically take the line and column number data and pass that to credo:

mix credo web/views/post_view.ex:22:7

So the nice thing here is that it calls out exactly the code in question, then has a quick explanation of why it's a big deal. Here we're shadowing a function name with a local variable - if we were to remove or rename that variable but forgot to change it where it's used, it has the possibility of causing really weird bugs and the compiler wouldn't catch it.

This one was an actual warning. The other categories tend to focus on code readability and refactoring opportunities. You should really prioritize the actual warnings if you're looking for things to fix up.

You can also add a configuration file to your repo to configure credo. I've linked to an example in the episode's resources section.

Summary

This was just a quick look at Credo, which is a pretty impressive tool. I plan to run it in my Continuous Integration pipeline and archive the output for production applications, so that in the event that we're looking for something to do we can just grab a few warnings or refactoring suggestions and make the code incrementally better. See you soon!

Resources