How to detect and safely remove dead code

Don't just ignore it

Joel Clermont
Joel Clermont
2024-04-29

Last week I attended php tek in Chicago, and one talk that caught my interest was on the topic of "zombie code". This is dead code that is not actually in use, but hasn't yet been deleted from the project.

When we join a project, it's common for us to bump into dead code. I might be refactoring something or asking a question and the project owner will say "Oh we haven't used that in a couple years".

This isn't just confusing for newcomers, but it can slow down maintenance of a project as a whole. Sometimes the code is easily identifiable as dead by using simple static analysis. Other times, especially when there are lots of dynamically built class or method strings, it can be dangerous to remove code.

One thing I learned from the talk at php tek is the term "tombstone". This is a technique where you add some logging to a suspected piece of zombie code, run it in production for a period of time, and then check to see if it was actually used. I've used this technique before, but I never knew there was a specific term for it.

One other insight from the talk was that a tombstone doesn't need to track what called the code. Just keep it simple and just logged that it was called, then you can go deeper with the analysis later. This is a simpler approach than what I've done in the past.

There are some libraries to help you create and monitor tombstones, but honestly, it's such a simple concept, you can just leverage Laravel's built-in logging mechanism to do it without adding a dependency.

As a final thought, if you know there is some unused code in your project and you haven't yet deleted it, there is no time like the present. Go clean it up and lighten the load. If you ever need it back, that's why we use version control!

Hope this helps,

Joel

P.S. Last week we opened up our private Mastering Laravel community to new members. We'd love to have you join!

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼

Level up your Laravel skills!

Each 2-minute email has real-world advice you can use.