Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Joe Fallon:
Immutable Objects in PHP
Aug 27, 2015 @ 16:53:36

Joe Fallon has a post to his site talking about immutable objects in PHP, objects that once the property values are set they cannot change.

When I first learned to program, I made many objects that were mutable. I made lots of getters and lots of setters. I could create objects using a constructor and mutate and morph the heck out of that object in all kinds of ways. Unfortunately, this led to many problems. My code was harder to test, it was harder to reason about, and my classes became chock full of checks to ensure that it was in a consistent state anytime anything changed.

[...] Now, I favor creating immutable objects. The folks over in the functional camp are super excited about this concept. However, it’s been around for quite a while and it has so many benefits.

He talks about how immutable objects make it easier to not only test code but also allow for more rational reasoning about their contents. He points out that they also make it easier to understand the state of an application should an exception arise. He then gets into some examples of immutable objects, creating an ImmutableClass and a ImmutableClassBuilder to help create instances based on values provided.

tagged: immutable object introduction class builder example benefits

Link: http://blog.joefallon.net/2015/08/immutable-objects-in-php/


Trending Topics: