I have a data structure consisting of thousands of medium sized (hundreds of byte) objects, which each represent a subset of a larger dataset. This isn't optimal for several reasons (complexity when analyzing larges scopes, strain on garbage collector, etc.)
Conceptually, you can imagine the objects representing for example meteorological data for a day, when the dataset as a whole is the data for a year (say). Trivial example:
class YearData
{
private readonly DayData[] days = new DayData[365];
public DayData GetDayData(int dayNumber)
{
return days[dayNumber];
}
}
class DayData
{
private readonly double[] temperatures = new double[24];
public double GetTemperature(int hour)
{
return temperatures[hour];
}
public void SetTemperature(int hour, double temperature)
{
temperatures[hour] = temperature;
}
}
In a refactoring effort I have tried to move the data to a single object representing the whole dataset, but to keep the rest of the code unchanged (and simple), I need the objects representing the subset/segment of data. Example:
class YearData
{
private readonly double[] temperatures = new double[365*24];
public DayData GetDayData(int day)
{
return new DayData(this, day);
}
internal double GetTemperature(int day, int hour)
{
return temperatures[day*24 + hour];
}
internal double SetTemperature(int day, int hour, double temperature)
{
temperatures[day*24 + hour] = temperature;
}
}
class DayData // or struct?
{
private readonly YearData yearData;
private readonly int dayNumber;
public DayData(YearData yearData, int dayNumber)
{
this.yearData = yearData;
this.dayNumber = dayNumber;
}
public double GetTemperature(int hour)
{
return yearData.GetData(dayNumber, hour);
}
public void SetTemperature(int hour, double temperature)
{
yearData.SetData(dayNumber, hour, temperature);
}
}
This way I can have a single huge and long lived object, and I can keep many small short lived objects for the analysis of the data. GC is happier and doing analysis directly on the whole dataset is now less complicated.
My questions are, first: does this pattern have a name? Seems like it should be pretty common pattern.
Second (.NET specific): The segment object is very lightweight and immutable. Does that make it a good candidate for being a struct? Does it matter that one of the struct fields is a reference? Is it bad form to use a struct for an type that appears mutable but which in fact isn't?