preparing for const, final, and invariant

Daniel Keep daniel.keep.lists at gmail.com
Fri May 18 02:52:34 PDT 2007



Aarti_pl wrote:
> I want to ask about something opposite to above example...
> 
> Will it be possible to pass ownership of object? I mean that when you
> pass object by reference to function/class/member variable you can still
> modify this object from outside of function/class. It breaks
> encapsulation in program.
> 
> Example:
> 
> import std.stdio;
> public class TestX {
>    char[] value;
>    char[] toString() {
>        return value;
>    }
> }
> public class TestMain {
>    TestX x;
> }
> 
> void main(char[][] args) {
>       TestX parameter = new TestX();
>       parameter.value = "First assignment";
> 
>       TestMain tmain = new TestMain();
>       tmain.x = parameter;
> 
>       parameter.value = "Second assignment";
>       writefln(tmain.x);
> }
> 
> Notice that tmain.x value has changed although I would like just to set
> once, and have second assignment to parameter illegal... When using
> setters and getters problem is even more visible....
> 
> How to achieve proper behavior with new final/const/invariant/scope??
> 
> Regards
> Marcin Kuszczak
> (aarti_pl)

I don't think the new const, final & invariant are going to help you
any.  Basically, you seem to be complaining that reference semantics
are... well, reference semantics.

That's like complaining that water is wet :P

There's a few things I can think of to get the behaviour you want.

1. Use a write-once setter for 'value'.  You can either create a
nullable template, or use a flag to ensure external code can only set it
once.

1.a. A "nicer" approach would be to set it in the constructor, and then
either mark it "final" (with the new final), or only write a public
getter function.

2. Use a struct instead; no references, no indirect changes.

3. Take a private copy of the object by writing a .dup method.

	-- Daniel

-- 
int getRandomNumber()
{
    return 4; // chosen by fair dice roll.
              // guaranteed to be random.
}

http://xkcd.com/

v2sw5+8Yhw5ln4+5pr6OFPma8u6+7Lw4Tm6+7l6+7D
i28a2Xs3MSr2e4/6+7t4TNSMb6HTOp5en5g6RAHCP  http://hackerkey.com/



More information about the Digitalmars-d-announce mailing list