PSR-1 2.3 Side Effects Rule
Asked Answered
P

1

28

I have a question Regarding PHP Basic Coding Standards PSR1. PSR 1 Rule 2.3 states:

Rule 2.3 Side Effects

A file SHOULD declare new symbols (classes, functions, constants,
etc.) and cause no other side effects, or it SHOULD execute logic with side
effects, but SHOULD NOT do both.

The phrase "side effects" means execution of logic not directly related to
declaring classes, functions, constants, etc., merely from including the file.

"Side effects" include but are not limited to: generating output, explicit
use of 'require' or 'include', connecting to external services, modifying ini
settings, emitting errors or exceptions, modifying global or static variables,
reading from or writing to a file, and so on.

Can someone give me an argument that supports use of this rule? Or, explain the benefit of this rule, and why it is important or a good idea to implement. This will help me support full implementation of PSR 1 and make a good case.

Polled answered 8/11, 2012 at 22:16 Comment(0)
E
49

The idea is that when a class is auto-loaded, the state of the application should not change. Any state-modifying code (code that actually executes) should be in a different set of files.

This makes it predictable and forces you to keep your logic in class methods, and implicit.

Remember that coding standards exist so people code in a similar style. The benefit in adopting a coding standard is that your codebase is self-consistent and consistent with other projects following the rules.

PSR-1 largely follows what everybody was already doing. If you feel the need to execute logic in the same place where a class is defined, there is very likely a better place or approach.

Lastly.. don't adopt PSR-1 for the sake of. If you have a valid reason to not follow the rules in certain spots, break the rules. They're not laws. Common sense reigns supreme.

Source: I'm one of the contributers of that document.

Exiguous answered 8/11, 2012 at 22:30 Comment(2)
Is making the code testable to test one practical reason to do this? i.e. it is easier to load and test a function / class if there is nothing else going on in the file that declares the function / class.Chromosphere
@Chromosphere Yea that could be a reason. I think I'd generally expect a class auto-loading to not have any side-effects other than new symbols to be defined.Exiguous

© 2022 - 2024 — McMap. All rights reserved.