If you’re unfamiliar with PSR-7, it’s what finally gave PHP a standard in regards to the design of Request and Response objects for those libraries and frameworks that deal with them, unifying the way we approach the input and output of web apps, in a way. One of the defining traits of PSR-7 is that the objects are immutable.
With PSR-7 defined and adopted by the most important / popular packages out there, more and more, and more immutability-as-a-cure-for-everything discussions began popping up in recent months.
Immutability is a concept that has its roots in functional programming languages like Scala, where it makes sense. When the entire language works with functions and focuses on producing new output from immutable input, it’s really quite natural and intuitive to work with. But PHP is not a functional language per-se.
The immutability advocates from the posts above (among others) claim making classes final and dealing with immutable value objects helps you code defensively, but I beg to differ. I believe that all it takes to “code defensively”, is to architecture your components well, code to interfaces, and write good documentation (if it’s other people’s contributions you fear).
The variables PHP builds are single-request (except in special circumstances), so making them immutable by default is madness - take for example the PSR-7 Request: who in their right mind changes a request mid-way of processing it, and then loses track of the change? Is this really something to fear and defend against?
This seems like another one of those “Hey look, PHP devs discovered functional programming, haha” punchlines people will be throwing at us soon - we’re pushing into PHP practices which don’t really belong, and aren’t really necessary.
Sure, immutability is fine. And yes, value objects are fantastic, especially for big projects and teamwork. But let’s not overuse these practices - let’s not push too far and overcomplicate things for no reason. People tend to get too taken up in the most current fad, and this recent, in my opinion, far too hard a push for immutability will do little more than to confuse new developers before, next year, we decide it’s trendy to hate getters now.
Use value objects where appropriate. Use final where appropriate. Avoid setters and force immutability where appropriate. But don’t say that the only way to get a changed version of an object is to return a new object populated with the values from the old one, because that’s just putting a paper mask with the word “immutable” scribbled on it over an object’s face and calling it a day.
What do you think about the immutability wave? Justified? Am I completely wrong here?