# Ways to avoid the needs and the musts of global variables??

This topic is 2576 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Quote:
 Original post by RubiconWhy do you want to remove global variables? Are the uni professors pushing fixes to non problems again
Quote:
 Original post by return0Otherwise, the OP and other new programmers will end up thinking that the complaints against singletons/globals are unjustified scare tactics from ivory tower academic types who have no place in games.
You know, if I knew a single ivory-tower academic type who *had* an opinion on coding practices (beyond documentation), my respect for them would increase threefold.

If you go google for all the "singletons evil" articles from a few years back, you will find that 90% of them are from industry types, not academia. Codebases in academia are generally awful: legacy code mashed together with last year's fad design patterns, in some unpleasant language/API combination that no one has ever heard of [smile]

So before you going blaming good coding practices on academia...

##### Share on other sites
I agree, and I think that people who disagree like to attribute what they perceive to be bad advice to some impractical academic strawman. I only mentioned it to cover that base.

##### Share on other sites
That'd be me then. I can't begin to guess what goes on in university as there weren't even relevant courses in this stuff when I was the right age.

All I can comment on is what I see new grads pumped full of when they turn up. It seems to me they have all sorts of priorities, but shipping code is somewhere near the bottom (right below debugging techniques). It's an easy stretch to see that lecturers don't actually ship any code, and then I can join up my own dots.

Maybe they just get terrorised by being told that everyone else on their teams won't be able to code for toffee and they'll have to keep coming in on Saturday to fix other peoples' problems or something.

Dunno really, but people have to get this mentality from somewhere that globals in your code is worse than failing lotcheck, and it's certainly not borne in the workplace, as like I said earlier, it doesn't go on in any of the many workplaces I've seen.

(And true enough, I've never worked on mission critical server back ends or flight dynamics, just games)

##### Share on other sites
There's also the odd situation whereby every now and again a holy war starts up over utter trivia. It's globals today. Next week it'll be along the lines of "How can you ship games without even reading the GoF book?". A week later it'll be "How can you ship your game without boost and smart pointers?". We've already skirted along the "How can you ship titles without using agile/scrumm/blah?" and that'll come up again too.

The bottom line is that if someone brainwashed me into adhering to all this crap, I'm willing to concede that my productivity might go up by 1%, maybe. But my productivity is already much higher than anyone elses in most places I've worked at. And massively higher than the kind of guys who want to unit test a particle system. And judging by how little time I spend at other peoples desks, my code seems to be somehow useable also.

The unescapable fact of the matter is that all of us "luddites", the few that oppose the motion in forums, are the ones the producers come running to when the project is in the shit. It really is, I get it a lot. Even right this minute (well, over the holdiday) one guy I worked with in the past is talking to me about sacking his freelance team and getting us to start again from scratch.

"Just get it done" is the most important factor in a programmers make up, but this goes totally unsaid. Well, unsaid by those that don't actually think it's top of the list and are therefore just seat filling drones- and those guys should just do what they're bloody well told.

##### Share on other sites
Disclaimer: I am stepping into this thread as a community member, and by the unwritten law of GDNet, I hereby forfeit my ability to exercise any moderator power in regards to this thread or any side discussions that may spin off of it. Should things get ugly, though, I will enlist another impartial mod to come clean up as he/she sees fit, so don't take this as permission to get out of line.

I always find it interesting how arrogance tends to manifest in direct proportion to sheer naivete.

Rubicon, please let me be blunt with you for a moment.

You're probably a decent programmer. Maybe. I don't know, I've never worked with you, never seen your code, only read your advice handed out on GDNet - and that I've rarely found to be worth the cost of the paper it isn't printed on. Maybe you're being honest when you say you're so much better than all your colleagues, I don't know that either. But I don't think you should be parading that around as some kind of justification for your opinions.

Suppose Mozart's ghost were to show up here, and start talking about how he's so much better than all his contemporaries, and how in his opinion all this nonsense about playing successive notes in a consistent key is overrated hogwash. We'd probably all roll our eyes at Mozart and move on. Maybe a few of us would feel compelled to point out that he's a bit of a moron for making such statements in a world where musical theory is extremely well understood. Maybe a couple of us more observant folks would realize that he's basically arguing against something he was tremendously good at doing subconsciously, and therefore consider the whole thing an elaborate troll. Whatever.

In any case, if one of history's greatest and most recognized musical geniuses were to show up and start decrying basic music theory as academic bullshit, do you really think anyone but the most naive and ignorant fool would seriously listen to him?

What I'm driving at is this. You're talking as if you are a remarkable programmer. That may or may not be true. But you also talk as if you can thoroughly discount a lot of things that are proven good theory - and not just by theorists, but by those with practice in the trenches who have seen real code and know the real differences between following these guidelines and breaking them.

I have two questions, both rhetorical, which I'd like you to ponder. First: do you really think you are so much smarter than everyone else, that their input is literally worthless? Secondly, do you really think you can be as productive as you claim without at least instinctively doing things right, regardless of how you think you got there?

It's ironic that you keep worshiping this notion of "just ship code" as if it were so holy and superior to all other perspectives. The funny thing is, I also place a huge emphasis on shipping code. But I think there are some subtle differences in our ideas of what it means to ship.

To you, apparently, it means "kick something - anything - out the door and if you can't understand or fix it by yourself later, then fuck you."

To me, shipping code means four things:

• Producing work which accomplishes the goals that were set forth for the project

• Accomplishing objectives in a reasonable - often pre-agreed - time frame

• Writing code that both I and anyone else can maintain and understand far into the future

• Taking responsibility for the problems that will inevitably arise and working proactively to prevent or at least minimize them prior to shipping - then supporting and reacting to situations as they arise post-ship

Frankly, I think my idea of shipping code is a lot more professional and respectable than yours. And everyone I've worked under in my career is bound to agree.

I also find it interesting that you mention that people come to you to get the job done.

This is true for me as well.

Except there's a key difference: I get it done according to my (very high) standards, and I do so by embracing the advice of people with more intelligence and experience than myself. I get repeat business because I can prove in any environment that I am good and that my skill merits the investment in my time.

You seem, by your words, to get by sheerly on contrast with the alleged incompetence around you.

I could drop into a studio full of far better programmers than myself and still hold my own and do solid work, and still earn a good reputation, still earn repeat business.

Could you?

Also, you expressed some particularly interesting opinions about automated testing and its relationship to games. Have a look around the job postings for the industry for "SDET" positions. I'm sure you have no clue what that means, so look it up. Be educated.

Just because you're so damn sure of yourself doesn't make you right.

##### Share on other sites
*deleted*

I did type a long litany addressing every accusation, but defending myself that way looked churlish and I really don't need to.

If you have it in your head that I'm sort of twat and want to read that much bile from between the lines then be my guest.

[Edited by - Rubicon on January 2, 2011 5:55:23 PM]

##### Share on other sites
Just to summarise:

Yes, I do come across as arrogant at times and I am extremely dismissive of new ideas for the sake of it. Because they're usually shite or address non-problems or are just too damn fiddly to be viable.

However, I've been working in the games industry practically since it started and have never been out of work for a single day. I've shipped about 50 titles over that time. I can think of only two that went out late and one that went out too buggy.

I won't be right all the time, and someone may well have a better opinion on a particular topic than I. But if you think my work record doesn't qualify my opinion on matters as being valid and useful, even if you don't agree with some of them, then what exactly is this board for?

You want the blind leading the blind now?

[Edited by - Rubicon on January 2, 2011 5:14:30 PM]

##### Share on other sites
Quote:
 Original post by RubiconI am extremely dismissive of new ideas for the sake of it. Because they're usually shite.
The issue I take with your stance is that most of these aren't new ideas just for the 'sake of it'. Some group of people have distilled a sizeable body of experience, and came up with a few principles that they find make life easier.

Now it may well be the case that your own body of experience does not support the same conclusions, but being openly combative to every, single, new, idea, just for the sake of it, doesn't really sound any better than what you are fighting.

Now, I don't entirely disagree with what you are saying. But as far as I can recall, you have only been on this warpath for a couple of weeks - so may I ask why the sudden conviction to swing everyone to your own viewpoint?

edit: new forum bug - can't link to individual replies, because the postbox interprets hash-prefixed numbers as unicode escapes...

##### Share on other sites
I think my tolerance capacitor just fills up with certain things and I need to discharge it once in a while.

I'm only dismissive of this stuff (boost, unit tests, design patterns, multi-inheritance etc) because I *am* ignorant of a lot of it! Or have been bitten by it.

Pardon the arrogance again, but I've been put on the spot: The reason I keep harping on about "just get it out" is that I really do have a reputation for getting done in a day what other experienced guys might take two or three over. It's what I do. Don't come to me for a physics engine as I'm not too hot on that stuff, but do come to me if you want standard stuff punting out at a massive rate. And most of game dev is standard stuff. We use a bought in physics engine for example.

So my point is this. If I truly am faster than average to the point of having a rep for it, and I still don't know how to use boost, don't use agile development, don't do unit tests, then what is all that stuff meant to be achieving?

Regarding the advanced coding stuff, again its more down to practicality than some sort of binary racism. A lot of people attacking my stance seem to fall back to comments about solidity and maintainability and self defence, and that's a fair argument.

However, if you strip away templates, multi inheritance, excessive operator overloading, boost, etc then the code becomes so simple to look at that a newbie can fully understand everything I wrote after a quick scan - and that's the best sort of maintainability you can have in my book. Sure the lack of templates can cause extra work, but someone already said that the actual typing isn't a big part of your day and I agree. So it's not much work to just drop them and keep your code readable by anyone then, is it.

And finally, the reason it winds my up when someone says "you're wrong, industry experts have said this..." is because I consider myself to be that soldier too. When we started our own company we made all these things above illegal in our coding practices and still got lots of good work done on time for good profits. And our code is never a problem to port, is always readable and is regularly maintained. So it's a proven, viable operating practice whether that goes against the grain or not.

And that's just not just meant as "bully for me". The point of the above is again purely practical. We get shit done on time and to budget without all the new this and that, so for newbies just starting out I completely advocate bypassing the lot - you can write games without it and learning general game code paradigms is a big enough ask in general. Why complicate matters with side issues?

Hope that helps to explain where I'm coming from a little better than the ridiculous bile version from the previous poster...

(EDIT: PS. I see you linked my comment in the scene graph thread. In that case I was just getting po'd at people not attempting to answer the question, but showing off how new thinking they are instead. My previous couple of comments I thought were more than useful and constructive. But I swear someone at some point will say that integers are old thinking...)

EDIT2: I just checked out all those links and I see they're not to what I assumed they'd be, hence the above wall o' text. I've mentioned the first one, but the other three weren't openly combative at all. I advised against the methods being discussed with described insight of fails, not any latent hatred.

[Edited by - Rubicon on January 2, 2011 7:16:03 PM]

##### Share on other sites
My opinion is that globalised and static data is an old fashioned practice that actually complicates code. Just pass stuff around as parameters and be happy.

I do enjoy a global logger from time to time however, but that's because I mostly use logging as just another debugging tool - so I don't want to side-track from debugging a problem just to go about engineering the access to a logger, I just want to a grab a logger instance, use it and move on. I'm perfectly willing to accept that I may have to go and pull those logging statements out later; but I find that to be both less time consuming and simpler compared to having engineered the logger in properly to begin with.

##### Share on other sites
I think my real distaste for your attitude stems from your insistence on generalizing from your own experience as if nobody else will ever - should ever - experience anything different.

My point is, briefly, this: maybe it works great for you to do things the way you do. But to assume that your personal path is the optimal route for everyone is the height of both ignorance and arrogance.

These recommendations, best practices, tools - they don't exist because we feel like making a mess of things. They exist because they have concrete benefits to a certain class of people. You sit here and claim not to belong to the class of people who benefit from them; fine. Maybe that's true, maybe you just don't understand them well enough to benefit, I'm not arguing either way here. All I'm saying is that your attitude that nobody else should belong to that class of people is just... disgusting.

To then insinuate that people are unskilled, or unintelligent, or should be fired, or whatnot just for not agreeing with you... that, frankly, makes me feel a little sick.

Sure, maybe you really do find it best to cut your lawn with a toothpick and a butter knife. But don't you dare look down on me for finding it more efficient to use a damned lawn mower.

##### Share on other sites
Quote:
 Original post by ApochPiQI think my real distaste for your attitude stems from your insistence on generalizing from your own experience as if nobody else will ever - should ever - experience anything different.My point is, briefly, this: maybe it works great for you to do things the way you do. But to assume that your personal path is the optimal route for everyone is the height of both ignorance and arrogance.These recommendations, best practices, tools - they don't exist because we feel like making a mess of things. They exist because they have concrete benefits to a certain class of people. You sit here and claim not to belong to the class of people who benefit from them; fine. Maybe that's true, maybe you just don't understand them well enough to benefit, I'm not arguing either way here. All I'm saying is that your attitude that nobody else should belong to that class of people is just... disgusting.To then insinuate that people are unskilled, or unintelligent, or should be fired, or whatnot just for not agreeing with you... that, frankly, makes me feel a little sick.
Please stop this. As a moderator you should be fully aware that the whole purpose of a discussion forum is to illicit opinion. I can only offer my own and you can only offer your own and both are valid opinions.

But more than that, stop using emotive language to make me out to be some sort of Hitler. Just because you've read too much into what I say doesn't make you right either.

But just to be plain. I never insinuated anyone is dumb for not agreeing with me. Nor that they should be fired for disagreeing with me. In fact, I didn't say or insinuate any of the things you accuse me of, and I'm calling you out on it. Please fire away with your examples or be quiet.

##### Share on other sites
Collecting opinions is fine. But the fact of the matter is that some opinions are dangerous and potentially damaging to the people most interested in hearing them; I feel that yours belong to that category. The notion that all opinions are equally valid is borne of the same immaturity as a schoolchild's insistence that everything should be "fair."

Anyways, you asked for examples of the things I'm accusing you of saying. Fair enough. I don't think I read too far into any of this, though; if anything, I'm doing the best I can to give you the benefit of the doubt.

Quote:
 Original post by Rubicon"Just get it done" is the most important factor in a programmers make up, but this goes totally unsaid. Well, unsaid by those that don't actually think it's top of the list and are therefore just seat filling drones- and those guys should just do what they're bloody well told.

Quote:
 Original post by Rubiconif there are programmers in an outfit that pass a null into a function which then crashes and they can't figure out why that is and fix it quickly, they should get fired.

Quote:
 Original post by RubiconIf we ever ran into these notional problems that advocates dream up, then we'd probably re-examine our working practices. However they just don't. So we get on with churning out perfectly fine working code and f**k the standards comittees and globals police.

Quote:
 Original post by RubiconAnd just to finish off, what the hell is a unit test anyway? (rhetorical) I think I can guess and it sounds an awfully tedious way to avoid getting work done to me. If anyone asked me what our unit testing practices were in an interview, the very next thing to happen is me saying "thanks for your time" and handing him his train fare. We don't write unit tests, we write games.

I didn't even have to try to dig to find those, and they're all from this thread.

##### Share on other sites
But the way you are painting me is of course perfectly fair. okay, getting the rules now. And please don't "give me the benefit of the doubt" whilst lecturing about condescension

I see a load of random quotes by me above, but nothing that backs up your claim that I insinuate or downright assert that disagreeing with me is either dumb or should get you fired.

The "drones" comment is admitedly a bit harsh, and I'll even go so far as to admit I shouldn't have said that. But it's still nowhere near what you are claiming.

I think an apology is due, but we all know there won't be one as you now have a bee in your bonnet.

##### Share on other sites
I guess I will jump in this really quickly.

There is a huge difference between writing a game (in which much of the code will never be used again), and writing an application that is going to be maintained for many many years.

Maintaining code takes a different mindset then just creating code. Writing code that is easy to maintain is a whole different beast. I come from application dev world in which we know we will be working on this code base for a long long time.

Unit tests, pattern dev, inheritance patterns are all things that can be used to make that whole process easier. Now there is something to say about getting the product out the door, but when you have to start working on that upgrade that people are going to pay about 1/4th of the original price, you need to have everything in place to make sure you can get it done without all the issues that could come up by just "getting it shipped".

Any time I have worked on a new project I was one of the ones that forced to issue to make sure we did it "right", instead of just getting it done. Did I ever regret that extra time spent? Not once.

To the main topic on here; globals. It all depends. A global that is set at start up and only read from is not really an issue. A global that can only be changed by a single object, is not really a problem. Globals that can be changed by anything at anytime are just not a lot of fun to debug.

theTroll

##### Share on other sites
Quote:
 Original post by TheTrollThere is a huge difference between writing a game (in which much of the code will never be used again), and writing an application that is going to be maintained for many many years.

The problem is if the game does well and a sequal is created sudden all that 'code we are never going to use again' becomes 'code which makes you want to stab the guy who wrote it in the eyes'.

We are dealing with this right now at work; various systems in the game were written to 'just work' and 'get out the door' (on a game which slipped by a year at that); one year after that, when the guy who wrote it had left, the rest of us (me as a new hire onto the team) were left to deal with code which, frankly, only just held together.

Systems with magic numbers all over them and no clue as to what they did; systems which only worked due to the way the old data was setup by the guy who original made it with undocumented limits which took one guy around two weeks to track down and figure out! Overly complicated system which could be reduced in complexity (and as a team we have vowed to rip them out and start again!) and fall apart at the slightest proding.

The idea of writing code like it'll never be touched again just makes me shake my head; unless what you do flops there really is no such thing.

##### Share on other sites
Yeah, I know, I was trying to explain the mindset.

I pretty much try to never write code that I wouldn't want to use again.

theTroll

##### Share on other sites
Yeah, wasn't meant as an attack or anything, more to highlight the dangers of such mindsets in general [smile]

##### Share on other sites
I should probably state at this point that "just make it work", at least from my mouth, does not mean "bodge it quickly".

What I'm really on about is to write some code to turn the wheels and make it a method called CCar::TurnWheels(float dt);

As opposed to thinking about what refactoring I can do to enable me to inherit CWheel from CCarPart and then consider a design pattern that best serves a wheel turning scenario and then unit testing whether it worked or not. By the time you've read that sentence, I would have my wheels turning. Well, ok. Ish! :)

And by global variable being ok, I mean TimeMgr=Engine->GetTimeMgr(); and not "Sprite[2].x++;"

##### Share on other sites
ApochPiQ, I think I am more aligned with your thoughts on engineering but I don't think you're necessarily being fair on Rubicon. I also happen to disagree with him a lot of the time, but that doesn't mean that his position is not legitimate, or that he is in any way trying to be vindictive.

This thread has covered a decent spectrum of opinions on the OP's topic, and has been quite interesting. I think it has also been useful because it shows the degree to which competent (if competence is dubiously defined as the ability to remain employed and ship/deploy games) disagree about fairly fundamental things, which probably isn't something that a new programmer would necessarily expect.

On that note, I've worked with people I've strongly disagreed with about many engineering practices, and the thing that I've learned is that you can't take it personally... it is frustrating to not "win" the intellectual argument, but that either means I'm wrong or that I'm not good enough at explaining my position.

##### Share on other sites
Thanks mate. It's restored the faith a bit to have an old sparring partner put his head above the parapet.

And I never actually expect to win one of these things. I do believe I'm right (or at least I have one version of arguably many rights), but I clearly never present my point the correct way as my main thrust is "get more done with less" which I would've thought should go down better that this! :)

##### Share on other sites
This thread might have run out of steam but let me throw in my bit.

I avoid global variables by not having any global variables.

Global variables are bad because globally mutable state is really really bad. What doesn't have state? Functions. Wait I need state somewhere! Static variables. No one complains about calling rand() from anywhere, though of course it stores state. The state is static, it can only be touched in that module (local, not global).

So the answer to the "global logger" scenario is:
void log_init(settings);void log_print(stuff);void log_shutdown();

If you need more than one, then it's not global anymore, and you need to handle the state.

If you need unit tests, just make an implementation of that module header that does nothing or has sane defaults.

##### Share on other sites
Ugh.. I shouldn't, but sleep isn't calling me yet so...

Quote:
 Original post by RubiconWhat I'm really on about is to write some code to turn the wheels and make it a method called CCar::TurnWheels(float dt); As opposed to thinking about what refactoring I can do to enable me to inherit CWheel from CCarPart and then consider a design pattern that best serves a wheel turning scenario and then unit testing whether it worked or not. By the time you've read that sentence, I would have my wheels turning. Well, ok. Ish! :)

Here that sound? It's the sound of everything you just said wooshing over your head because you are CLEARLY commenting on things you do not understand and that alone makes your advice suspect at best.

I mean, seriously, that sentence (for lack of a better term) was nothing more than technical gibberish at best.

Lets try and take each thing you apprently have a problem with here;
- Refactoring; a process which happens AFTER THE FACT to remove redundant code and clean up intent. This isn't something you'd do before writing the 'TurnWheel' function anyway.

- Inhertiance; often abused, sure, but modern thinking has very much pushed away from this to composition. You'll probably say this is nothing new and I'd agree and beyond short related chains I prefer to avoid it anyway. Frankly anyone who knows anything wouldn't advocate CWheel:CCarPart anyway unless there was very solid reasoning for linking the two types. Maybe the uni graduates you have a bee in your bonnet about would try to do such a thing but not those of us who you also seem to think are 'wrong'.

- Design Patterns; seriously, stop even trying with this you are just showing your ignorance constantly. Design Patterns are nothing more than a common language used to talk about things. A good programmer would be aware of them but wouldn't say "I need to do X, what pattern can I use?" they would say "I need to do X, how can I solve it?" and then later, when discussing it with someone else might say "Yeah, I used a flyweight for that" or "I hooked it up as an observer to do....".

- Unit testing; Again, something you don't understand and yet feel qualified to 'poo poo' as much as possible. If you knew anything about it you'd realise that a unit test for something like that could be a simple as;

-- Set wheel to known rotation
-- Apply function with known time step
-- Check that wheel position is at expected location

Or; set number, call function, compare number.

Finally, as I think I mentioned before; you do not unit test everything. Many things, by their nature, can't be tested. Other things should be tested because you need to check they are still performing to spec. Writing a test for a critical component is generally trivial and testing in general is VITAL for any large project where a bug could be introduced so it can be caught early.

So, here is a suggestion from one professional to another; if you want to rubbish as subject at least have the decency to learn about it first. Attacking something from a position of ignorance (which is what you are doing) just makes you, the attacker, appear ignorant.

Don't want to learn about it?
Fine.
What to continue saying "Well, I don't use this"?
Fine.
Just, you know, drop the "its clearly rubbish, despite the fact I don't know anything about it" line.

##### Share on other sites
Quote:
 Original post by CadetUmferNo one complains about calling rand() from anywhere, though of course it stores state. The state is static, it can only be touched in that module (local, not global).

You know, this makes me wonder how 'rnd' would react when being called from multiple threads at around the same time?
I wonder if the CRT is thread safe in that case...

##### Share on other sites

Quote:
 Original post by CadetUmferThis thread might have run out of steam but let me throw in my bit.I avoid global variables by not having any global variables.Global variables are bad because globally mutable state is really really bad. What doesn't have state? Functions. Wait I need state somewhere! Static variables. No one complains about calling rand() from anywhere, though of course it stores state. The state is static, it can only be touched in that module (local, not global).So the answer to the "global logger" scenario is:*** Source Snippet Removed ***If you need more than one, then it's not global anymore, and you need to handle the state.If you need unit tests, just make an implementation of that module header that does nothing or has sane defaults.

Or, store the state in private member variables of an object, "init" it in the constructor, "shut_down" in the destructor/dispose, and have a well defined API. Create these objects where needed. Then invert that dependency.

Now it's impossible to call "Log" before "Init". Yay!