in reply to Re^4: The fallacy of the *requirement* for read-only instance variables.
in thread The fallacy of the *requirement* for read-only instance variables.

Outside of threading, what type of "contexts" are there which could "share objects" with a risk that one of them might change it without it being a deliberate act on the part of the programmer to do so?

Say you have a $price1 object. It might be shared between $item1 and $purchase1. One might change the amount of $price1 in order to change the price of $item1, but that would be wrong, as it would result in the unintentional (not deliberate) act of altering the records of the purchase.

By limiting the ability to change the amount of $price1 (i.e. making Price immutable), one avoids this type of mistake. (One could also avoid the mistake by not sharing $price1, but that requires more memory.)

We actually do have a Price class here. It's an overloaded object that has an amount an a currency. It's immutable so this works:

$y->set_price( $x->get_price() ); my $price = $x->get_price(); $price *= 2; # Creates a new object. $x->set_price( $price );

There's no deliberate act to change $y, but it would change if Price was mutable.

Update: Added example.

  • Comment on Re^5: The fallacy of the *requirement* for read-only instance variables.
  • Download Code