-
-
Notifications
You must be signed in to change notification settings - Fork 1
What is immutability?
Immutability is a property of programming language variables or data structures that prevents their values from being modified after they have been created. In other words, once a value is assigned to an immutable variable or stored in an immutable data structure, it cannot be changed.
Immutability can be applied to various types of programming constructs, including variables, objects, arrays, and strings.
The advantage of using immutable data is that it makes programs more predictable, easier to reason about, and less error-prone. Since immutable values cannot be modified, there are no unexpected side effects from changing their values. This makes it easier to write code that is reliable and easier to debug. Additionally, immutable data structures can be safely shared between multiple threads or processes without the risk of race conditions.
If part of an application interacts with a JSON API and uses json_decode
to provide an object or associative array, the contents of the decoded data could be inadvertently changed from anywhere in the code. There would be no way of knowing if another area of code manipulates the data before your code accesses it.
As an example, take a look at this simple script below. It loads a JSON API endpoint, then passes the object to three functions.
$json = json_decode(file_get_contents("https://example.com/payment-details.json"));
setupBilling($json);
setupShipping($json);
chargeCustomer($json);
Now imagine it's your job to implement the chargeCustomer
function. How could you know that the setupBilling
or setupShipping
functions are not manipulating the object's contents before your function is called? There could be many negative effects to having a function mutate data in this way, so when dealing with Data Transfer Objects, it's safe to make them immutable.
Immutability is achieved by using a Data Transfer Object that can only set data once, without being cloned to another instance. Then, specifying this Type of object in your function's parameters means it can't accept anything else.
PHP.Gt/Json is an extension of PHP.Gt/DataObject that's built specifically for this use case, along with adding type-safe getters.
Visit PHP.Gt/DataObject to learn more, or see PHP.Gt/Fetch for a full-featured library that utilises JSON heavily.
PHP.Gt/Json is a separately maintained component of PHP.Gt/WebEngine.