I'm perusing a class that seems to utilize a nested class for private
fields. In a nutshell, it looks as follows:
1. I've never seen a technique like this. What's the big idea of lumping
"private" fields in a nested class?
This sounds to me like the Handle/Body pattern (Bridge pattern) that
allows you to detach/abstract the actual data from the interface to
that data so the two can independently vary from each other. I am
paraphrasing here so please allow me to illustrate. I recently
implemented classes similar to this but rather than go into all of the
intricacies of that project let's explore something a bit lighter.
class DataSurrogate
{
public Data (string name)
{
this.name = name;
this.id = Guid.NewGuid();
}
string name;
Guid id;
public string Name { get { return this.name; } set { this.name =
value; } }
public Guid { get { return this.id; } }
}
class DataUser
{
DataSurrogate data;
public DataUser(string name)
{
this.data = new Data(name);
}
public string Name { get { return (this.data == null) ? "Default
Name" : this.data.Name; } }
public DataSurrogate ReplaceData(DataSurrogate newData)
{
DataSurrogate oldData = this.data;
this.data = newData;
return oldData;
}
}
Now, obviously the above example is hardly useful but with it you
should be able to see how easy it is slide the underlying data in and
out of the containing object without having to recreate it. There are
a number of uses I can think of but a very convenient one is for
testing a variety of data values. Consider also a more complex data
surrogate wherein other classes are also using the same surrogate
object. Assume also you have a data provider that can arbitrarily
change all of the data in one operation. This pattern would allow you
to change that data without having to also recreate and reinitialize
all of the classes that depend on it.
2. If it is a big idea, wouldn't a struct be better than a class?
Sure, why not? Depending on the data you are abstracting a struct
would be just fine and potentially better suited to the situation.
I hope my explaination did not confuse matters any worse.
John