http://qs1969.pair.com?node_id=686482


in reply to const correctness

First off, Perl has Readonly and constant which provide the same functionality. And, every single (usable) OO framework on CPAN allows you to specify accessors as separate from mutators, should you so choose.

Now, to some commentary.


My criteria for good software:
  1. Does it work?
  2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?

Replies are listed 'Best First'.
Re^2: const correctness
by fergal (Chaplain) on May 14, 2008 at 13:56 UTC
    Perl has Readonly and constant which provide the same functionality.

    They're not the same thing. const is not about constructing immutable values it's about being able to declare that "in the following code, the contents of this variable should not be modified, if you see me trying to modify it, throw a compile-time error".

    It's also about making a promise in your API which the caller knows will be kept because it has been checked at compile-time. Of course you can force the compiler to let you break the promise using a cast but it can't happen as an unanticipated side-effect or typo.

      In compiled languages, its also about giving the compiler clues about optimisations it can safely perform, especially in multi-threaded environments. A const value can be safely shared without locking, or moved into a register and not re-read for every reference. The current big problem is the lack of transitivity of const.


      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.
Re^2: const correctness
by amarquis (Curate) on May 14, 2008 at 14:00 UTC

    When first I learned programming in a formal environment (first computer science classes), I was very concerned about properly noting my "never to be changed" variables to the compiler. When I got to Perl, it was one of the first things I looked for, but was confused by the differences between and the possible subtle traps within Readonly and constant. So, I stopped using them, even though it bothered me to do so.

    And today my own thoughts are more in line with your point number two. My own code makes obvious what should not be changed internally, and the external interface protects/hides everything from outside code. I like giving myself as much protection against myself as possible (strict, warnings, etc.), but now feel like const would be redundant with the checks implicit in the way I code.