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.


In reply to Re^5: The fallacy of the *requirement* for read-only instance variables. by ikegami
in thread The fallacy of the *requirement* for read-only instance variables. by BrowserUk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.