salezica
salezica

Reputation: 76919

C, design: removing global objects

I'm creating a small Avida-style life simulation. I started out with a very basic, everything-is-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 that every other function got something out of. Now, I must localize the object and pass pointers around. Thing is, mostly everyone needs this object. I've thought of three possible solutions:

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

I'm fine with new ideas, and will provide whatever information about the program you want to know.

Thanks in advance!

Upvotes: 6

Views: 123

Answers (3)

Pete Wilson
Pete Wilson

Reputation: 8694

I have to agree with @Carl Norum: there is nothing wrong with the global config setup you have now. You say that everybody "got something out of" it. As you know, the problem with globals comes when everybody writes into them. In your case, the config info truly is needed globally so deserves to be global.

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

See, storing pointers everywhere isn't going to really solve the problem: it will only add a layer of indirection that will merely disguise or camouflage what are, in reality, the global accesses that are making you nervous. And that extra layer of indirection will add juuuuust enough room for juuuuust a teeny-weeny little bug to creep in.

So, bottom line: if stuff is naturally global then make it global and don't worry about the usual widespread received wisdom that's mostly correct but might not be the right thing in your application. To always be bound by the rules/propaganda that CS teachers put out there is, imo, the perfect example of a foolish consistency.

Upvotes: 3

Nektarios
Nektarios

Reputation: 10371

Global variables are awesome. Spend your time actually getting something done instead of refactoring for no reason. Every company I have worked at uses them heavily.

Ask yourself if you're actually gaining anything by moving it to an object you're just passing around everywhere. Might as well save yourself the extra complexity..

Upvotes: 2

Puppy
Puppy

Reputation: 146910

Go for B, unless profiling proves it to be a problem. On most machines, the memory required to store a pointer is very, very trivial.

Upvotes: 0

Related Questions