so what exactly is const supposed to mean?

Chris Nicholson-Sauls ibisbasenji at gmail.com
Mon Jul 3 12:39:06 PDT 2006


Hasan Aljudy wrote:
> Lars Ivar Igesund wrote:
> 
>> Hasan Aljudy wrote:
>>
>>> damn, this doesn't sound too good.
>>> I for one don't give a damn about const, so why should I be bothered to
>>> think about the constness of my code/classes and add "mutable"
>>> qualifiers all over the place?
>>
>>
>>
>> Hmm, this sounds bad, for you ... you are aware that immutable objects 
>> are
>> your guarantee in multithreaded system to have safe sharing of data? Have
>> you looked at any well designed library in languages like C++, Java or 
>> C#?
>> Try to count the immutable classes present, I think you'll find quite a
>> few.
> 
> 
> Let me repeat:
> Is there anything preventing anyone from creating immutable classes?

Technically no.  Although at present, there are precisely two possible methods, and both 
require wrapping every single field up with a D-style property.  (True properties could 
actually have the potential to make this simpler... but we don't have those either.)

Method #1 - Write the class as innately immutable, then write a mutable subclass.  This is 
the methodology at work in Mango, for example, where the module mango.io.FilePath actually 
defines two classes, FilePath:Object and MutableFilePath:FilePath.

Method #2 - Same as above, but with one class that has a pair of methods (mutable() and 
immutable() for example) that activate/deactivate mutability, usually locking on something 
such as instance of another class (the identity of which doesn't particularly matter). 
For (quick'n'dirty) example:

# class Foo {
#   private Object mlock ;
#
#   public void mutable (Object o) {
#     if (mlock is o)
#       mlock = null;
#   }
#
#   public void immutable (Object o) {
#     if (mlock is null)
#       mlock = o;
#   }
#
#   private void checkLock () {
#     if (mlock !is null)
#       throw new Exception("immutable object");
#   }
#
#   /* ... everything else ... */
# }

Now then, if in class Foo we want to define some property bar as an int, we now have no 
choice but to do something like this:

#   private int p_bar ;
#
#   public int bar () { return p_bar; }
#
#   public int bar (int x) {
#     checkLock;
#     return p_bar = x;
#   }

Imagine if class Foo has twenty different fields/properties, most of which surely don't 
require any special processing -- meaning that the property wraps are pointless like the 
example above, although canonical.  Also imagine you have classes you wish to use as 
immutable, which you have no control over the design of: then you have to write an entire 
wrapper class, fully re-implementing the original class's readable interface.

Ew.

-- Chris Nicholson-Sauls



More information about the Digitalmars-d-learn mailing list