Style/Structuring question: One vs. multiple global objects
Lutger
lutger.blijdestijn at gmail.com
Mon Jul 2 18:49:24 PDT 2007
Henning Hasemann wrote:
> Say I have a game engine in which nearly all parts including the
> engines user need to access some global values.
> Example for such would be the screen width & height, the current main
> character, the currently displayed scene, the jukebox-object which does
> sound stuff, etc...
First think about if they really need to be global variables. Does you
renderer need to access the sound system? Does your window class need to
know the main character and that character need to know the screen width
and height? All these things you mention do not need to be global.
> I used to have one single global game object which stores all the other
> things mentioned above because deep in my mind there's a "global
> variables are evil" burned in.
Global variables are not evil, but they can be 1) costly in terms of
maintenance and bugs and 2) indicative of a less than clear design. Same
goes for cyclic dependencies. But, like goto, it's not a hard rule.
> Now where the stuff is getting more complex, this often leads to some
> "forward reference" issues because the game module needs to import a
> lot (scene module, character module, etc...) but also lots of modules
> need game.
> So this leads to circular imports which somehow leads to that forward
> reference stuff.
>
> Would it be a better idea to have multiple global objects for the
> different things? I.e. a "currentScene" global in the scene module, a
> "mainCharacter" global in the character module etc...?
>
> What would you do?
>
> Henning
That would already be better, but these globals can be eliminated
altogether. Some of the things I do:
- think about what really needs access to these variables, often a lot
of code does not use all things you are tempted to make global
- isolate these 'globals' in one place and let other parts use that. For
example screen width and height can be used by the window class and then
some select few classes depend on the window class. Problem solved.
- use abstractions such as interfaces when appropiate
More information about the Digitalmars-d-learn
mailing list