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.
3
u/Business-Decision719 11h ago edited 10h ago
Ideally a structure should represent data snippets that are logically grouped together, to the point you could think of them as a single "thing," with the fields acting as whatever different pieces that kind of "thing" is naturally and obviously expected to have. It's almost like a simple form of OOP basically. The struct is a custom data type so it should make sense to have values of that type (or "objects" of that "class" if you want to think of it that way). If it also makes sense for values of that type to be pieces of a larger struct then so be it.
If you're going out of your way to make a struct nested or not, then you're probably going about it wrong. If all the pieces of a certain kind of thing are fairly distinct then it might make sense as a flat struct and that's fine. You wouldn't make other structs to nest inside it it just because. It can be subjective, and maybe one person would nest something someone else wouldn't, but nested or flat is not really the goal in and of itself.
For example, having a
positiondata type makes sense. A position is a kind of "thing." I can say "give me a position." It's a place somewhere. In two dimensions it would have an x and y coordinate. I can split it apart and say "give me the x coordinate of this position." You don't necessarily have to store an entity's x and y coordinates as a position object but it's a very defensible choice to do so.A "stats" struct is a little more iffy. What are you going to give me if I tell you to "give me a stats?" Its own type name pretty much announces announces that it's just sort of an amorphous cloud of data. Why doesn't an x coordinate belong there, or a renderable texture? They just don't apparently. Someone might want to group together health and armor if there's a reason for them to go together, but it's not nearly as obvious that there's some single unit here apart from the rest of the entity. (It doesn't immediately pop into my mind to say "give me the current health of this stats" as opposed to "give me the current health of this entity.") Of course maybe it could make sense to group certain stats or to have a little namespace inside the entity object to contain them; my point is that forcing
struct entityto only be made up of other structs, to the point that you need a "wastebasket struct" to throw ungrouped data into, is not really a sensible use of structs. That doesn't mean a flat struct is inherently better just by being flat.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.
8
u/SystemSigma_ 13h ago
I find nested structs to be helpful in reducing the scope of function consumers.
Thus I pack things together because they make sense only together and belong to the same "state".
As per the binary layout, there's no difference in the two, the compiler should produce the same packing and aligment.
11
u/Gold-Produce9591 13h ago
it depends on how much the other structs are used (i.e. position, stats and renderable). if they are only used in the entity struct, there is no point in them existing
2
u/cursed-stranger 13h ago
How many people working on this project? If it's just you, then what is easier for you, is better. In memory it should be the same, so there is no difference if its flat or nested. If there is more people working on it you should get common agreement which to use. Probably nestet is better in that case due to separation and different people can work indepentendly on different parts.
Btw, it's just my opinion, not some universal pattern so treat it just like that
2
u/thisisignitedoreo 12h ago
If you're directly embedding the structures into other structures (which, for small things like position or something, you should) and not putting them behind pointers, there is zero runtime overhead, and, I think, it provides a nice way of (a) accessing fields (I think it's nicer to
player->position.xthanplayer->x) and (b) copying structs around, e.g.some_entity->position = player->position. It ultimately doesn't matter though, if you like to be more verbose, go for it, if you don't, you're not missing out on much.2
u/reality_boy 12h ago
Whatever works best. There is a very old concept in computer science that says you should come up with an abstraction that describes the problem set. And use that to help organize the logic and keep things simple.
How you setup the abstraction is not super important. What is important is that the abstraction is relatively simple, easy to understand, and has good coverage with the problem set.
Obviously a wildly complex abstraction (10 nested classes to make a yes/no decision, etc) is going to be confusing to use and maintain (ai slop tends to make a lot of this)
Easy to understand is one of the foundations of coding, and most people undervalue it. You want everyone to get what is going on.
Coverage is where it counts. You will hear a lot about refactoring. That is a fancy way of saying the code we have is not designed to solve the problem we have (or is not efficient, readable, etc). Learning to model your structures around the problem set is a real art. You learn by reading a lot of code and then trying things out and reflecting on how well you did.
2
u/WittyStick 12h ago edited 11h ago
I would use nested structures. It's likely you're going to need
struct positionelsewhere, and it would be pointless typing(struct position){ ent.x, ent.y }each time to wrap it, when you could just writeent.position.Also, designated initializers will make it easier to initialize your entity without having to remember the order of fields.
There will be no difference in performance either way, so don't think that matters. Just use whatever you'd expect to see if it weren't your own project for example - because in 6 or 12 months, you probably won't remember what order you defined things in.
If you don't want to write
ent.stats.healthyou can use a macro or inline function:Macros may be more suitable if you don't want separate
getandsetfunctions.There's also a more boilerplate option - an opaque pointer - where you define it once and no longer need to care how the structure is defined because it is not accessible to other modules. This option lets you change the structure without breaking code that uses the header.
position.hentity.hentity.c2
u/FedUp233 5h ago
I’d base it on two things, both related to how they are going to be used.
If you need a type of structure in a number of other structures, like a position or coordinates or something then I’d make that a separate struct and use it multiple places and hopefully come up with a set of functions for manipulating it that I can also call from several places. I’d try to keep the functions that mutate the data I a nice set and hopefully other places in the code that need to use some of the data are read-only uses. In this case it makes sense to have a separate structure embedded in the overall structure - it allows you to pass a pointer to the piece that these lower-level functions manipulate.
Similarly if it’s all going to be used together, are the functions that use it going to call other functions to manipulate a subset of the data, even if there all part of the same set of code and the data is only going to be used in that one overall structure. Again, then it’s nice to be able to write these helper functions so they only know about their part of the data and pass them a pointer to the substructure. It will also help prevent strange couplings forming later when someone just decides they want to look at some other piece of data in these helpers that wasn’t used there before and that coupling gets hidden deep in the code. If the helpers only see there data it will force any of these type couplings to be brought to the surface by either passing the additional data as parameters to the helpers or refactoring the structure.
If functions are going to need access to all the data to make decisions, then it might as well be a flat structure, again unless you want helpers to do the manipulation of some piece, like coordinates. Keeping it in a flat structure will reinforce that it’s all going to be used together in the algorithms that use it.
2
u/P-39_Airacobra 13h ago
I think theres something to be said for not having nested pointers, because layers of pointers introduce a lot of complexities like more complicated initialization and nulls. It’s also less memory efficient, unless you plan on sharing the inner structures all over the place.
1
u/Plastic-Usual-3412 12h ago
Introducing nesting is convenient when you are reusing the defined struct and related function calls. But until then you are better off keeping it simple without unnecessary nesting imo.
1
u/CryptoHorologist 12h ago
When you open your toolbox and see a drill, you're seeing a nested thing composed of other things. If you have hundreds of loose screws in your toolbox, then you have problems. If you have a box of screws, then you're probably going to be a lot happier. When you use a drill, you use the whole thing, not the pieces (generally). The same thing applies to your software concepts. A position is often a better model of the thing you use than the x and y coordinates separately. If you don't like composition and types, then you're probably going to have a hard time creating maintainable software.
1
u/an0th3rbrick 12h ago
in a single project like a game where you're passing entities to every function there isn't much advantage to nesting. but if you're using lots of libraries that take subsets of your entity - like positions - then nesting allows you to pass a pointer to the sub-structure
1
u/Ok_Outlandishness906 12h ago
IT depends of usage. the good thing of nested struct is that you can hide visability with them and pointers
1
u/misplaced_my_pants 8h ago
I think you have your answer, but look into this: https://en.wikipedia.org/wiki/AoS_and_SoA
1
u/sciencekm 7h ago
I normally create individual structures for data that are logically together. Then I use these to create bigger structures.
1
u/nhermosilla14 13h ago
If you can afford flat ones, it's much easier to deal with those. Nesting is something that usually comes with extra cognitive load, so it should be avoided unless there's a very good reason to use them IMHO.
0
u/GhostVlvin 11h ago
What about
0
u/[deleted] 12h ago
[deleted] — view deleted comment