Continuing from the question that I asked here: C++ multi-dimensional data handling
In my example: I have many Chips, each Chip has many Registers, each Register has many Cells, and each Cell has many Transistors. I asked whether to use one complex STL container for them, or to implement full classes for them. And, as advised, I chose to implement full classes for them. I have:
class Chip { map<RegisterLocation, Register> RegistersPerLocation; }; class Register { map<CellLocation, Cell> CellsPerLocation; }; // etc..
Now, I need to fill the data to the classes, and I can’t decide: Should reading the data be responsibility of these classes, or should they just wrap the containers and the reading will be done outside.
I mean I have to choose one of the following: Either:
class Chip { map<RegisterLocation, Register> RegistersPerLocation; public: void AddRegisterPerLocation(RegisterLocation, Register); }; void ReadChipData(Chip & chip) { for (RegisterLocation loc = 0; loc < 10; loc++) { Register reg; ReadReg(reg); chip.AddRegisterPerLocation(loc, reg); } } void ReadReg(Register & reg) { for (CellLocation loc = 0; loc < 10; loc++) { Cell cell; ReadCell(cell); reg.AddRegisterPerLocation(loc, cell); } } //etc...
Or:
class Chip { map<RegisterLocation, Register> RegistersPerLocation; public: void ReadData(); }; void Chip::ReadData() { for (RegisterLocation loc = 0; loc < 10; loc++) { Register reg; reg.ReadData(); RegistersPerLocation[loc] = reg; } } //etc... void ReadChipData(Chip & chip) { chip.ReadData(); }
Thank you.
If you are thinking of tying the reader/writer to the domain objects in order to follow the principle of encapsulation, you are correct to a certain extent. But remember: You bind not just any action, but a valid behavior. Valid as in makes sense for the object in the domain.
Another thing to keep in mind is separation of concerns. Serializability is not a
Chip‘s intrinsic behavior — modeling that into the domain object would be unfair IMO. YMMV.Separate the reading(and writing) from the classes. As the library does. Expose iterators if you have to. And you can overload the ‘<<‘ and ‘>>’ operators for syntactic sugar 😉
A minor nit on the classes — a template based approach looks so promising.
Here’s some code I cooked up: you can try the following as well. (I’ve successfully compiled and run this on a MS VS2005 but check it out on your system. Also, can someone fix the tabbing — feeling too lazy to do this :P)
Caveat: Haven’t tested, so there may be quite a few compiler errors/warnings. But this should give you an idea of what I am trying to say.