How to Teach Your Team Private Method Sorting in 3 mins

When I started PHP in 2004, all you had to do is to learn a few functions to become the most senior dev in your town. Nowadays, devs have to learn a framework, IDE and coding patterns to get at least to an average level.

Instead of reading 346 pages of Clean Code, you need to produce code and learn as you read it at the same time. There will be never less information than it is today.

That's why effective learning is a killer skill. Today we learn how to sort private methods in 2 mins.

Why is Private Method Order so Important?

This simple class is in your code now:

<?php

class SomeClass
{
    public function run()
    {
        $this->call1();
        $this->call2();
    }

    private function call3()
    {
    }

    private function call2()
    {
    }

    private function call1()
    {
        $this->call3();
    }
}

Thanks to Gregor Harlan, there is a coding standard OrderedClassElementsFixer, that already takes care about public/protected/private elements order.

But what about these private methods - are they ok for you?


When you read such a code for the firs time, you might think:

"Be able to read down the file from top to bottom like a newspaper article,
which would naturally suggest that helper methods appear after the methods they are helping.
This would lead to maximum readability of the code structure."

Nice Theory, Bro, but... Real-Life?

It's easy to spot and correct the example above...

<?php

class SomeClass
{
    public function run()
    {
        $this->call1();
        $this->call2();
    }

    private function call1()
    {
        $this->call3();
    }

    private function call2()
    {
    }

    private function call3()
    {
    }
}

...but in real life pull-requests are usually longer than 20 lines:

Taken from my 5 days-old-PR

Nor junior nor senior dev is able to check the proper private method order in these big chunks of code.

Unless...

...somebody or something does it for you.

"Automate everything that brings you more value until you die
compared to value lost to create it
."

I've already mentioned a coding standard. There is now a new fixer coming to Symplify/CodingStandard 5.2 that does exactly what we need in a split of the second:

# ecs.yml
services:
    Symplify\CodingStandard\Fixer\Order\PrivateMethodOrderByUseFixer: ~
vendor/bin/ecs check src

You might need to re-run the command few times, because of the new order of private methods will automatically change calling order. But that's it:


Let finish with Martin Fowler quote:

"Any fool can write code that a computer can understand.
Good programmers write code that humans can understand."

I think we're coming to times, where:

"Any computer can write a code that humans can understand."


Have fun!


Typo? Fix it, please  and join 49 people who build this website