Its refreshing when you solve what appears to be a nasty problem with a simple and clean solution. It's an even better feeling when you solve it with Computer Science fundamentals. I solved something this morning by releaning how acces modifiers work (access modifiers in C# in my case).
We have a basic data transfer object that has some private state that handles change tracking. Something such as:
1: public class ProductDTO
2: {
3: private bool _isDirty = false;
4: private string _name;
5:
6: public string Name
7: {
8: get { return _name; }
9: set
10: {
11: if ( value != _name )
12: {
13: _name = value;
14: _isDirty = true;
15: }
16: }
17: }
18: }
This of course is a contrived example, but it illustrates the crux of my problem.
The _isDirty flag is managed internally and marked private as you'd expect. What I need to do is transfer state from one instance of ProductDTO to another. I need the public state as well as the private/internal state. Over the years I've been lulled into thinking of private members as things that cannot be accessed outside of an instance. This isn't true. Private members cannot be accessed outside of the class. In other words, two instances of the same class can happily access each other's private/internal members.
With this lesson relearned, I'm able to create a Copy() method such as:
1: public void Copy(ProductDTO copy)
2: {
3: _name = copy.Name;
4: _isDirty = copy._isDirty;
5: }
Note the get of the _isDirty from the copy instance.
I'd forgotten this how Access Modifiers work and from the majority of code I've seen in recent years, most developers out there have as well. You typically see numerous forms of encapsulation violation or leaky public contracts to accomplish something like this.