C, design: deleting global objects

I am creating a small life simulation in the style of Avida. I started with a very simple, all-global 600-line program in a single file to test some ideas, and now I want to create a real design.

Among other things, I had a global configuration object from which any other function received something. Now I have to localize the object and skip the pointers. The thing, basically, everyone needs this object. I thought of three possible solutions:

  • a) Store the configuration object global (the simplest, although not very solution)

  • b) Keep signs wherever they are. (quite easily, although a waste of memory, since some small structures are required with the usual old data it).

  • c) Creating factories for POD types that need access to the factory to perform all operations on them.

Of my ideas, only (c) sounds logical, but I do not want to unnecessarily complicate the structure. What would you guys do?

I am fine with new ideas and provided any information about the program that you want to know.

Thanks in advance!

+6
source share
3 answers

I have to agree with @Carl Norum: there is nothing wrong with setting up the global configuration that you currently have. You say that everyone "got something." As you know, the problem with globals occurs when everyone writes to them. In your case, configuration information is really needed all over the world, so it deserves global.

If you want to make it a little more decoupled and protected - a little less global, then why not add some read / write access procedures.

You see, storing pointers everywhere will not solve the problem: it will add only a layer of indirection that simply masks or disguises what is actually global access that makes you nervous. And this extra layer of indirection will add enough space for juuuuust a little small mistake to sneak in.

So, the bottom line: if the material is natural global, make it global and don’t worry about the usual widespread wisdom, which is mostly correct, but may be wrong in your application. Always being bound by the rules / propaganda that CS professors expose is, imo, a perfect example of a dumb sequence.

+3
source

Global variables are awesome. Spend your time doing something, not refactoring for no reason. Every company I worked with uses them heavily .

Ask yourself if you are really typing something by moving it to an object that you just walk around. You can also save extra complexity.

+2
source

Go to B if profiling does not prove that this is a problem. On most machines, the memory needed to store the pointer is very, very trivial.

0
source

Source: https://habr.com/ru/post/892406/


All Articles