r/C_Programming • • 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.

17 Upvotes

37 comments sorted by

View all comments

0

u/GhostVlvin 11h ago

What about

struct entity {
  struct {
     int x;
     int y;
  } position;
  struct {
    int health;
    int armor;
  } stats;
  struct {
    string filename;
  } texture;
};