views:

85

answers:

3

Lets say you have a property like:

Person person1;


public Person Captin{
    get{
        return person1;
    }
    set{
        person1 = value;
    }
}

public void SomeFunction(){
    Captin.name = "Hook"
}

In this case if you set the name on the property we know that the new name of Hook will get applied to the underlying value of person1. What if our implementation were a little different say:

public Person Captin{
    get{
        return ReadCaptinFromDisk();
    }
    set{
        WriteCaptinToDisk(value);
    }
}

public void SomeFunction(){
    Captin.name = "Hook"
}

In this case for the underlying value to get set properly we need to have the Captin's set code called as part of the assignment to Captin.name.

I am interested in knowing if the parameter set code will call the set on assignments of field or method calls on property references. especially for this kind of situation where the value needs to be propagated to disk (etc.).

+4  A: 

Each time you access your property Captin it will read from disk. But if you change the property 'name' it will not write to disk. It will only write to disk if you do something like

public void SomeFunction() {
   Person p = Captin;
   p.name = "Hook";
   Captin = p;
}
JSC
+1  A: 

As @Joe notes it will not write to the disk. I just wanted to add that it is because you are only using the getter, not the setter. @Joe's example uses both.

In my opinion, this is both a really bad use of a getter and violates separation of concerns. You should have a data layer that handles persisting the data. The logic of this should not be in your business object.

tvanfosson
I am mostly interested in using cached copies of objects
minty
A: 

The property's setter will only be called when someone actually assigns to it directly.

As for whether your code is okay or not: it's a matter of documentation.

Whenever you have a property which returns something mutable, you ought to indicate whether what mutations to it will do. Are you returning a copy of your "real" data, or is it the real data itself? This comes up very often when a property (or normal method) returns a collection of some kind - it is mutable? What will happen if I change it?

If you document your property explaining that the data returned is just a copy, and changes won't be reflected anywhere, that's fine. If you leave it ambiguous, that's when you'll get problems.

Immutability removes these concerns, of course...

Jon Skeet