Track Possibly Dead Code with Coverage Tool
What is dead code? Simply put, it is code that is never executed.
Dead or unused code is at best a pain and at worst problematic. It takes effort to maintain, including unit tests, makes your code-base bigger and more difficult to handle, especially for new engineers your hire. Even worse, you can sometimes have dead code that is highly complex (or that introduces significant complexity to the overall system) and, if you don’t realize it’s dead, you may end up “standing on your head” to get other code to work properly with it. And all this for nothing.
Fortunately, there are dead code identification tools that exist out there that can help. The problem, though, is that they statically analyze your code and try to understand which code is used and which is not.
In our example, we will use the Istanbul package. The idea here is to run this against actual production use. The way to achieve this is fairly simple:
- Take one production server out of the pool.
- Shut down your Node.js application.
- Run it again using Istanbul; instead of
istanbul --handle-sigint cover app.js.
- Wait for your application to start and put the server back in the pool.
- Depending on your traffic and architecture, you can leave it like this for a few minutes, hours or days. The
--handle-sigintis meant to be used with long-running processes, which is exactly the case with your web server.
- Take the server out of the production pool again.
- Stop the Istanbul process. Once again the
--handle-sigintoption is helpful: You just have to kill the process using the
kill -s SIGINT [istanbul PID].
- Istanbul will write the code coverage report in the
coveragedirectory and exit.
- Start your Node.js application in a normal way again and put the server back in the production pool.
- Explore the HTML coverage report to discover what code is unused.
You might be concerned about response time overhead. From my experience, the server running Istanbul had a response time around 5% higher than without it. In any case, the code coverage server should always be monitored closely.