Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PSR-2 Opening braces for control structures

Tags:

php

psr-2

One thing which I am trying to understand why PSR2 has curly brackets for class and method on new line and for the rest not. I would say it's much easier to read code if curly brackets are always on a new line.

class Foo extends Bar implements FooInterface
{
    public function sampleFunction($a, $b = null)
    {
        if ($a === $b) {
        }

Can somebody explain what is the logic behind:

Opening braces for control structures MUST go on the same line, and closing braces MUST go on the next line after the body.

like image 211
Zdenek Machek Avatar asked Nov 19 '15 13:11

Zdenek Machek


1 Answers

My understanding of the reasoning here is basically to prevent blocks of contiguous code from becoming excessively long.

For example, say I have an 50 line function written in PSR-2 style. If that function contains 10 if() conditions and 5 loops, then my function under your rules would be 65 lines long.

Since it's a single function, I need to be able to work with it as a single entity, so it is really helpful to be able to see it all at once. With a 50-line function, that's feasible. It gets a lot harder if the function is 65 lines long.

In fact, looking at my editor window right now, I can see 30 lines at a time, so even a 50-line function is a bit too long to manage easily without resizing or removing the docked panels in my IDE.

Now I know that clean code rules would say that a 50-line function is far too long anyway and needs to be refactored. I'd agree with that. But guess what: functions with 50 lines or more are pretty common; I have to deal with them all time time, and the less unnecessary white space they have in them, the easier they are to work with.

Ultimately, however, this is just one interpretation of the root reasons behind it.

The real reason PSR-2 is this way is because that's how the consensus of opinion fell. They surveyed all the frameworks and others who had established PHP coding standards. All those different standards existed because people had sat down and thought about how best to format their code. They didn't agree because it is an opinionated subject, but there were broad areas of agreement and that was what went in to forming the PSR standards.

like image 158
Simba Avatar answered Sep 24 '22 22:09

Simba