I was checking out PSR-2 to make sure my coding style was correct, especially since I saw in the news release that Yii 2 follows this convention. I was really surprised to see in paragraph 4.2 that:
[color=#333333]Property names SHOULD NOT be prefixed with a single underscore to indicate protected or private visibility.[/color]
Obviously, this is not strictly observed in Yii 2 because I’ve seen instances of it :
Example from Advanced Template LoginForm.php model:
class LoginForm extends Model
public $rememberMe = true;
private $_user = false;
And also, I have no clue why they would be against coding this way, it seems very intuitive to indicate private or protected by using an underscore. I want to do my best to write code according to the standard, I’m a big believer in having a standard, but there is no explanation to this. I did a quick Google search and found nothing.
I’m leaning towards ignoring the standard on this issue because using the underscore just seems right and I want to follow the coding style of Yii 2. But on the other hand ignoring standards can be dangerous and lead to bad habits. I know this is an incredibly microscopic issue, but anyone have any thoughts on why they would be against the underscore for private properties?
An argument in favour of the PSR-2 standard: if you change the status of a property from protected to public, you have to refactor all references to it.
The underscore in the name reminds me of to the old programmer’s habit of prefixing a variable’s type in its name (e.g. “floatAmount” and “strCustomerName”), which was popular in older languages when IDE’s were nonexistent. But now these habits are considered a bad practice by authorities such as Robert C Martin (see book “Clean Code”).
Because of this, I would say that your IDE should notify you about a variable being protected, instead of a naming convention that will probably be violated by many people. So I would vote in favour of conforming the Yii2 codebase to the PSR-2 way.
Thank you, I really appreciate your answer, it was very thorough and makes a lot of sense, especially on the refactor issue. I just read Clean Code, it’s a good read. On the other hand, the underscore is very effective in what it communicates. It will be ineresting to see what the Yii 2 team does in the future. I have to think about what this means for me personally. Thanks again for a great answer.
Assertion, not assertation. Probably a poor choice of words regardless. From your quote:
What are your valid reasons for prepending class variables with underscores? I also dislike seeing it, and I tend to think it reflects poor design choices when you need to prepend public member variables with underscores to imply they shouldn’t be accessed directly.