Remove Dead Public Methods from Your Code

We already have sniffs and rectors to remove unused private methods. But what about public methods? If you're creating open-source packages, public methods might be used by anyone.

But what if you're creating an application - you can remove unused with peace in mind. There is only one problem to resolve - find public unused methods.

Too long to read? Look at 3:45 min practical video by a friend of mine Jan Kuchař.


As we code on an application for many years, some methods may be replaced by a few new-ones:

 $person = new Person('Tomas');
-$person->getFullName();
+$person->getName();

If the application is complex, we may not know if the old method is still in use anywhere:

<?php

class Person
{
    /**
     * @var string
     */
    private $name;

    public function __construct(string $name)
    {
        $this->name = $name;
    }

    public function getName()
    {
        // ...
    }

    public function getFullName()
    {
        // ...
    }
}

We don't have to manually read the codebase file by file. PHPStorm can help us examine each public method and where they are being used.

Just right-click the method call ("provide" in the picture) and select "Find Usages".

It took us 5-10 seconds to find out that getFullName() is a dead method. Great job!

Can we Find Them Faster?

Now do the same for all the other public methods.

I consider Symplify project quite small, at least compared to private web applications. Yet, there is over 684 public methods. Even if we remove public methods from test fixtures, there will remain ~ 500 public methods:

500 * 5 secs = 2500 secs ~= 41 mins

...and we don't talk about brain wasted on linear operations. This is not the way.

How to find them in 20 Seconds?

There is one little sniff in symplify/coding-standard only few people know about. Set it up:

# ecs.yaml
services:
    Symplify\CodingStandard\Sniffs\DeadCode\UnusedPublicMethodSniff: ~

And use it:

vendor/bin/ecs check src

Magic?

Not really. The sniff goes through your code and:

Then just skip false positives, that are called in yaml configs or in strings - and that is it!

You'll be surprised, how many methods are dead in your code :)


Happy coding!