r/C_Programming • u/yughiro_destroyer • 13h ago
Flat structures VS nested structures?
Hello!
I have this deep conflict that has been with me for months now. How is it better, flat structures or nested structures? Or what do you prefer?
Flat example :struct entity = {int x = 20;int y = 40;string texture = "mario.png";int current_health = 100;int current_armor = 100;}
Nested example :struct position = {int x = 20;int y = 40;}struct stats = {int current_health = 100;int current_armor = 100;}
struct renderable = {string texture = "mario.png"}struct entity = {position position;stats stats;texture texture;}
I have tried to use nested structures as often as possible because that's the norm but they are becoming a pain in my experience. Mostly, it comes down to boilerplate, the risk of getting paths wrong when there's too much nesting and theoretical purity where I find that a property would've worked better in another component.
But with flat structures? I get much better results, more directness, easier debugging and less cognitive load as a property is defined in only one way, even if the names get longer or repetitive. Also, that's how computers like to think and as a CS engineer, I learned how computers think before learning how humans program so I lean towards more old school polling / procedural algorithms.
If I were to make an analogy of how that makes me feel, it would be like owning a big tools box. When I open the box, I can instantly see and pick or place the drill, the screwdriver, the screws and whatever else is there. But with nesting... if feels like after opening the tools box, that the drill has it's own mini-box, that the screws are in another box and so on. I prefer seeing the whole picture at once instead of always having to deal with involvement at micro-scales of a big thing.
Also, I noticed that older games like Doom are closer to flat structs. The thing is, my game isn't very complex in terms of gameplay and it features multiplayer matchmaking. And it's on the server side where I noticed that a flat structure would be much easier for debugging, serialisation and overall faster development speeds.
View all comments
23
u/Dependent_Bit7825 13h ago
The nice thing about hierarchy in your data structures is that you can take a pointer to a piece and give it to a function that only needs to understand that pieces. This makes it easier to keep functions narrow and focused, and to not let access to unrelated things creep in.
Let's say you have a function that formats the position as a string:
`bool format_position(char *dest, size_t max_len, const char *position)` looks much better to me than `bool format_position(char *dest, size_t max_len, int x, int y)` and that difference grows as the number of members you want in `struct position` increases.
I personally get annoyed when every function takes a pointer to some massive monolithic struct.