Doom 3 Source Code: Beautiful 399
jones_supa writes "Shawn McGrath, the creator of the PS3 psychedelic puzzle-racing game Dyad, takes another look at Doom 3 source code. Instead of the technical reviews of Fabien Sanglard, Shawn zooms in with emphasis purely on coding style. He gives his insights in lexical analysis, const and rigid parameters, amount of comments, spacing, templates and method names. There is also some thoughts about coming to C++ with C background and without it. Even John Carmack himself popped in to give a comment."
Beautiful code but (Score:5, Funny)
I'll be here all week.
Re:Beautiful code but (Score:5, Funny)
Re: (Score:3)
I think the patch for using flashlight and keyboard simultaneously would be something like "headlamp" or "teeth" instead of duct tape, though.
Re: (Score:3)
It was better then Uwe Bolls movies.
Re:Beautiful code but (Score:5, Insightful)
I did. No issues. Hint: The dark parts are supposed to be dark.
Re:Beautiful code but (Score:5, Insightful)
Re:Beautiful code but (Score:4, Insightful)
F.E.A.R.s sparse cut sense were better then the lights on lights off. There were also stretches in F.E.A.R. through well lit area's that were devoid of enemies. Only to be ambushed later. I wouldn't trash on F.E.A.R. so much.
I only played the 1st version and not the expansions.
Re: (Score:3)
Re:Beautiful code but (Score:4, Funny)
I did. No issues. Hint: The dark parts are supposed to be dark.
Clue: It's almost a necessity to see what your shooting at, the walls or bad guys.
Doom 1 FTW!
Re:Beautiful code but (Score:5, Funny)
John Carmack: The Kanye West of Video Game Programming.
"Imma let you finish your Dragonborn DLC in a minute, but DOOM 3 has the cleanest source code of all time. OF ALL TIME!"
Re: (Score:3)
In retrospect, I think timing is what hurt Doom 3 more than the darkness. Doom 3 was released at the same time LCD monitors started to take off, problem was that LCD black levels at the time were horse manure. I saw my friend playing it on his and it looked awful. The unfixed drawbacks of new tech hurt the game's reception among many.
Re:Beautiful code but (Score:5, Funny)
// TODO : rehire Romero, Petersen, Hall, McGee, Prince.
There, fixed. The engine may be fantastic, but Doom 3 is a horrible game that can't hold a candle to the previous titles. Or at least it can't hold a candle and a gun at the same time.
Re: (Score:2)
Re: (Score:3)
Daikatana and Alice were far from perfect, but they're still more enjoyable than Doom 3.
Re: (Score:3)
Did you actually play Daikatana?
I did. I quit before the end of the first level. An absolutely horrid game. Doom 3 I at least lasted about 30% of the way through the game before throwing in the towel. It was mostly the repetition, the constant stuff jumping at you. It's a very fatiguing game - I could probably make it through it if I took breaks to play other games every so often.
Re: (Score:3)
Did you actually play Daikatana?
I'll say only this: I wish there'd been an option to murder your companion, then respawn him so you could murder him again.
Re: (Score:3)
Re:Beautiful code but (Score:5, Insightful)
Speak for yourself. I thoroughly enjoyed Doom 3. Quake 4 as well. I actually modded in more self-shadowing and flashlight shadows into Quake 4 - wasn't dark enough.
Re:Beautiful code but (Score:5, Interesting)
Daikatana and Alice were far from perfect, but they're still more enjoyable than Doom 3.
I think you hit the nail on the head there, but possibly not in the way you mean.
Doom3 was an absolute masterpiece of atmospheric gaming, but it was just too much. It set your nerves on edge in a way that meant playing for more than an hour or so was just too stressful. I love the levels, the monsters, the story (ok, its basic but what do you want from a FPS) but I just find playing it burns me out too quickly. It is just too good at making you feel uncomfortable and claustrophobic without any respite.
I was just thinking back to Doom as I type this and from memory the big difference is that Doom had more variety with some levels set outside or in huge cavernous high ceilinged spaces. This variety is what made it great as it certainly had plenty of claustrophobia inducing levels too.
Re:Beautiful code but (Score:5, Funny)
Did we play the same game?
The atmosphere was interesting for the first 5 hours of gameplay, then it just got in the way of trying to play the game.
I got to the point where, every time I'd walk through a door, I'd look to the side and fire into the demon I *knew* was standing there. It was like the line in Last Action Hero where Arnold walks into his apartment, kid in tow, walks into the bedroom and puts a few rounds into the closet door. A ninja falls out of the closet, dead, and the kid says, "How did you know there was a ninja in there?" Arnold says, "There's always a ninja in there."
The only discomfort I felt was when I was squinting and cranking the gamma up just so I could see what I was doing.
The story sucked, too. What do I expect from a FPS? Deus Ex, Bioshock, System Shock, and all their associated sequels, etc. etc.
Re: (Score:3)
That's the thing, the atmosphere was absolutely wrong for the game! That creepy dark shit is what Doom was in the minds of elderly busybodies, but fans of the original expected something zany, fast, and over the top. [doomworld.com]
Limiting your market (Score:5, Insightful)
Re:Limiting your market (Score:4, Insightful)
Re: (Score:3)
maybe you should buy display that can do proper black levels...
I don't think you played Doom 3. doesn't matter how much you up the gamma the black areas are still black with some areas less black where you can sort of see where the path goes.
the re-release has a flashlight attached to player... doom3 has a great engine and is hampered by shitty, shitty, shitty level design. for a proper game done with the engine see quake 4.
Re: (Score:3)
You really don't get it, do you...
Re: (Score:3)
So we can still only have 2?
Not the best analysis (Score:3, Interesting)
Re:Not the best analysis (Score:5, Informative)
the concept of the bracket placement there is to emphasise indentation over bracketing. Once you "get" the view of it, it becomes a nice thing to look at, similar to python code.
I don't use it nowadays (too many coding standards that are written for the bracketing-style) but I appreciated it when I did. There's nothing wrong with the style, so I hope that you pass any code you review written in this style and focus on the important parts like readability of the code, good naming, commenting and the like rather than subjective opinions.
Re: (Score:3)
OK, I was a C/assembly programmer, never did much with C++. I always liked the square bracket style, and one thing I found very helpful was putting a short comment at the end of a block after the closing '}', even if it was just to show that it ended a 'for' rather than an 'if'. Example:
for (;;) /* forever */
{
misc code
if (1==x)
{
b
Re: (Score:3, Insightful)
While I prefer this style of bracing, the superfluous comments violate the D.R.Y. (Don't Repeat Yourself) principle. Might as well add a comment "break when x is one", as well. (also "forever" after "for(;;;)" or "while(true)" is again unnecessary and repetitive). I know your example is contrived, but these do serve as a prime example of bad comments. What's even worse is when down the line, "they" decide that you should break when x is two, but the comment remains unchanged. The point of comments that s
Re:Not the best analysis (Score:5, Insightful)
The whole concept of self-documenting code irks me too. Too often programmers use it as an excuse for not writing comments at all. Of course the code should be written clearly enough to the point where you don't need the comments to understand how the code will execute, but I don't think you should count on that as showing what and why that block of related operations is doing what it does. Comments can certainly be overused and underused and while commenting every single line is absurd in most cases, not commenting under the umbrella of "self-documenting" code can be detrimental as well.
Re: (Score:3)
I'm not a fan of the self-documenting style in some ways. Yes, the code should not be obtuse. But you also should not be forced to have all sorts of long variable and function names just to avoid comments, which I've seen plenty of people to do.
To me a comment should explain _why_ the code is doing what it is doing, since any programmer should be able to see what the code is doing (assuming it's not template heavy). Comments are there to provide communication with people who are maintaining the code. So
Re:Not the best analysis (Score:5, Insightful)
My take on comments:
Write the comments first, describing the overall goal, inputs and outputs.
Then write the actual code that implements the comments.
Re:Not the best analysis (Score:4, Interesting)
I noticed in their standards doc that they said all classes must start with "id". Classic Smurf naming convention. [codinghorror.com]
Re: (Score:3)
It's basically what you're used to. I was a passionate "brackets on their own line" style, but my present job's style guidelines do it with compacted way. After awhile I got used to it. It really only bites me when there's a long conditional that has to be two lines; meaning the second line of the conditional and first line of the body have the same indentation but no vertical separation, which I think looks ugly as hell. So I find myself doing things I don't really like to do: splitting into nested if
His Comment (Score:5, Informative)
In some ways, I still think the Quake 3 code is cleaner, as a final evolution of my C style, rather than the first iteration of my C++ style, but it may be more of a factor of the smaller total line count, or the fact that I haven’t really looked at it in a decade. I do think "good C++" is better than "good C" from a readability standpoint, all other things being equal.
I sort of meandered into C++ with Doom 3 – I was an experienced C programmer with OOP background from NeXT’s Objective-C, so I just started writing C++ without any proper study of usage and idiom. In retrospect, I very much wish I had read Effective C++ and some other material. A couple of the other programmers had prior C++ experience, but they mostly followed the stylistic choices I set.
I mistrusted templates for many years, and still use them with restraint, but I eventually decided I liked strong typing more than I disliked weird code in headers. The debate on STL is still ongoing here at Id, and gets a little spirited. Back when Doom 3 was started, using STL was almost certainly not a good call, but reasonable arguments can be made for it today, even in games.
I am a full const nazi nowadays, and I chide any programmer that doesn’t const every variable and parameter that can be.
The major evolution that is still going on for me is towards a more functional programming style, which involves unlearning a lot of old habits, and backing away from some OOP directions.
One might suggest that every good programmer, if they spend enough time improving, eventually moves toward a more functional programming style.
Re:His Comment (Score:5, Funny)
You remind me of my mom, who ends every political debate by stating that as people become older and wiser they tend toward being Republicans.
Reply with (Score:3, Funny)
Re:His Comment (Score:5, Funny)
Re:His Comment (Score:5, Insightful)
Re: (Score:3)
I think your point will go unnoticed by most of the people you are targeting
Which let me guess, also just happen to be the group with whom you primarily disagree. Oh the layers of meta-referential irony.
Re:His Comment (Score:5, Funny)
Mom, I told you nobody mods you up until you register.
Re:His Comment (Score:5, Insightful)
One might suggest that every good programmer, if they spend enough time improving, eventually moves toward a more functional programming style.
Good programmers don't move towards any one style, they become familiar with all of them and use them when and where appropriate. Just like computer geeks. You find Linux one day, install it, then fall under the spell of believing this year will be the Year of the Linux Desktop. But after awhile, you reach the second plateau of understanding -- Linux is good for some things, but not everything. The third plateau is no longer caring which tool you use, as long as its the best tool for the job.
Re:His Comment (Score:5, Interesting)
Yet the fourth plateau is the realization that if one vendor becomes extremely powerful, it tends to create huge barriers of entry for others and so your choice is reduced, sometimes drastically, and therefore it can be a good idea to just arbitrarily support competition even if what everyone uses is good enough right now.
Re: (Score:3)
Yet the fourth plateau is the realization that if one vendor becomes extremely powerful, it tends to create huge barriers of entry for others and so your choice is reduced, sometimes drastically, and therefore it can be a good idea to just arbitrarily support competition even if what everyone uses is good enough right now.
Also, divided government.
Re:His Comment (Score:4, Interesting)
1) A programmer discovers scripting languages and loves them, because they are so easy to write. Which is true.
2) The programmer discovers OOP, and realizes it makes code so much easier to read. Which is also true.
3) Then the programmer discovers functional programming, and realizes it makes it so much easier to avoid bugs. Which is also true.
You might say Python tries to combine all three of these features, which is true, though I offer no opinion on how well it does.
Re:His Comment (Score:5, Insightful)
4) The programmer discovers that functional languages do not provide enough access to basic data structures to write high volume state of the art applications, and rewrite many key portions of the code in C thus coming full circle.
Whoever writes a functional language that understands arrays and pointers will rule the world.
Re:His Comment (Score:5, Informative)
That's a fair point, but you have to pay closer attention to what Carmack wrote:
He said functional programming style, that doesn't necessarily mean using a functional language -- the point is that he is going in the direction of functional style when writing C++, which would involve, among other things, making as much as possible immutable (hence being a "const nazi").
Re: (Score:3)
One might suggest that every good programmer, if they spend enough time improving, eventually moves toward a more functional programming style.
One might suggest that ... but one would be wrong.
The very best programmers use the right idiom for the job. Sometimes a global variable is the right idiom.
Re: (Score:3)
Yeah, functional programming was all the rage in 640K with no on-chip cache hierarchy.
Good grief, functional programming predates the modern OOP idiom. John Backus's FP [wikipedia.org] dates to 1977. I was already proficient in APL which made reading his papers a fairly easy exercise. All this before C++ first appeared in 1983. I wrote all my code for the rest of the decade i
Re: (Score:3)
he's probably referring more to reference and method 'constness' which have semantic rather than just simply syntactic implications.
Mostly right, but a few problems. (Score:4, Interesting)
I've developed for large game and non-game projects, and each needs a different approach. Console games especially have serious problems with dynamic memory allocation (they don't typically have swap files and can die due to heap fragmentation) so you have to avoid a lot of convenience libraries like STL.
STL, however - especially in newer compilers that support C++0x - is actually quite good and is very, very robust. It's a good way to avoid a lot of the memory management bugaboos that happen when you *are* doing lots of dynamic/heap allocation. So I would very much endorse a sane amount of STL use in desktop code.
The other thing that rubbed me the wrong way here was public member variables. Since inlining and move semantics make getters and setters essentially free, there is no good reason to expose bare, public variables on anything but the simplest, most struct-like objects. The biggest source of weird, hard to trace bugs in our code at the game studio were often due to people modifying public members of other objects in unexpected ways or at unexpected times.
Having public, non-const member variables actually hurts a principle the author supports, which is "Code should be locally coherent and single-functioned". This means that an operation should do one thing and put you in one of several known and easily discoverable states, even on failure. That is, if I say, make this guy do X, then either he does X or he fails and ends up in a known state. If that state is available in the form of modifiable public data, then his state can get messed with at any point along that path by some other code, and the final state (in cases of success and failure) is not fully known. At the very lest, making data private means that only certain code paths can modify the data, and it's much easier to keep state coherent.
Anyway, that's just my $0.02.
Re: (Score:3)
"The other thing that rubbed me the wrong way here was public member variables."
I am puzzled by that as well. I guess his point is that: foo.setBar(foo.getBar()+3); is much more boring than foo.bar += 3;
I somewhat understand it and I wish we had automatic calls to get and set in C++ like it exists in C# to make core more beautiful.
Re: (Score:3)
Having also worked on (and lead) large game and non-game projects, I must respectfully completely disagree with you. The compiler might be able to boil someInstance.SetThing( someInstance.GetThing()*2 ) down to a couple of lines of assembly, but my eyeballs can parse someInstance.thing *= 2 much, much faster and (more to the point) more accurately. I think your potential for weird bugs just increases with the complexity of your syntax (and it's no trickier to catch one in a debugger than the other).
Re: (Score:3)
I'll tell you another reason to use public member variables: OOP doesn't have such a thing as a "public readable" variable, that is, a variable that member functions can change, and which can be read but not changed by non-member functions. The article lavishes praise on const, but this is one form of limited access a lot of OOP languages do not support.
There's a lot of dogma about coding practices, and I was happy to see the article take some of them on. Brevity is good. So, no useless comments, even
Re:Mostly right, but a few problems. (Score:5, Insightful)
The other thing that rubbed me the wrong way here was public member variables. Since inlining and move semantics make getters and setters essentially free, there is no good reason to expose bare, public variables on anything but the simplest, most struct-like objects. The biggest source of weird, hard to trace bugs in our code at the game studio were often due to people modifying public members of other objects in unexpected ways or at unexpected times.
There's zero difference between a public getter/setter pair and a public variable. Encapsulation and future proofing the interface? In a game codebase? You'll never use it, and if you did need it the code editor can search and replace for you. Meanwhile, writing piles of getter/setter functions is a waste of time. Unexpected modification of public values doesn't get any better when its done through a setter function.
Re: (Score:3)
In my experience this is a good way to hide your locking problems and avoid thinking about them. Which leads to deadlocks and excessively slow code. Because now if you want to modify 2,000 objects you have to lock each one individually instead of locking once and doing them in a batch. Then to fix that problem instead of rethinking the locking from the top and doing it correctly you get quick hacks like adding get_unlocked and set_unlocked to each object.
This is a must ... (Score:2)
Years ago I had to have this fight with a co-worker. His electric mode in Emcas was writing out everything as a single tab char, and doing the indenting on its own. The problem is, not everything obeyed this style -- not even a little.
I had to explain to him that since we weren't all using Emcacs, he needed to be sure to l
Re: (Score:3)
I never understood why this was a conflict for programmers. If the white space isn't syntactic, can't your editor just rearrange the code the way you want it? Just run it through a pretty printer before you work on it.
Re:This is a must ... (Score:4)
Except that will throw off diff.
Re: (Score:3)
This royally fucks up your version control history.
Most modern systems have the means to annotate a file - every line - with the revision that last changed it. It's invaluable if you want to work out which revision introduced a particular bug.
If you all have a whitespace war, every revision that touches the file will touch every line in the file.
Unless your merge driver is enlightened as well, you'll find it plays hell with your changes as well, every time you pull changes you'll get a conflict.
It's just ru
Re:This is a must ... (Score:4, Insightful)
Heh... if they're dictating tab width, they're doing it wrong. If you must have a certain tab width, you should be using spaces for everything or you lose the whole benefit of tabs - letting people choose their preferred indentation size.
Use tabs for indentation, spaces for alignment. That way you'll never go wrong. Looks like this was one of the less "beautiful" things about the Doom 3 code.
Comment-free programming (Score:5, Interesting)
I really liked this bit, because it's something I've been really focusing on for the last year or so, and I think it has significantly improved my code:
Comments should be avoided whenever possible. Comments duplicate work when both writing and reading code. If you need to comment something to make it understandable it should probably be rewritten.
Comments can be useful, IMO, but primarily only for generating documentation (think Javadoc or doxygen, etc.). Other exceptions include bits of code that perform highly-optimized mathematical calculations, in which case I think the best solution is to write a proper document and then add a comment linking to the document, and bits of code that do something which apparently could be done differently but for some other reason must not -- assuming that explanation doesn't belong in the doc-generating comments.
Other than that, I find it makes my code a lot better if every time I find myself wanting to write a comment to explain some bit of code's purpose or operation, I instead refactor until the comment is no longer necessary. Often it's as simple as taking a chunk of code from one method/function and pulling it out into another with a well-chosen name, or else introducing a variable to hold an intermediate value in a calculation, with a well-chosen name. Sometimes the fact that a bit of code is hard to explain is a strong indicator that the design is wrong, that stuff is mashed together that shouldn't be.
The bottom line is that I've found eliminating comments does more for improving the readability of my code than anything else, and I've gotten similar feedback from colleagues whose code I critique by pointing out that they can eliminate their comments if they refactor a bit.
Re: (Score:3)
Your comment example eludes to the operation being performed, but far more importantly it is documenting the data being used and generated.
Operations should be self-documenting. The function names and variable names, as well as the structure of expressions and flow control, should all conspire to inform the programmer about what steps are being performed as clearly as possible.
Comments on the other hand should conspire to keep
Re: (Score:3)
I second this. My thoughts exactly. I used to do a lot of embedded work, especially stuff that talks to other devices down RS422. Sometimes you just have to say WHY you are doing stuff in a seemingly counter-intuitive way. Even if your own hardware is sensible, more than once I've had to write comments along the lines of:
"/* Because the stupid device at the other end of the cable requires we do it this way round or it breaks. */"
I would also worry about referring to external docs; in most places I've wo
Most of His Admiration Is Not Technical (Score:5, Insightful)
And a note on the relative evil of comments; bad or not, well placed comments have saved me an awful lot of time when taking on maintenance of code bases in the past. Most of the time they can't present a design document to you, or if they do it covers the design at the start of the project, a decade and a half earlier. Code is a method of communication between two programmers, but if the code doesn't suffice to illuminate the design the original programmer had in mind, I'd really appreciate a comment explaining his thoughts. Especially if the particular section of code is complex, and especially if I'm the guy writing it and end up being the guy maintaining it a couple years later.
Re:Most of His Admiration Is Not Technical (Score:4, Informative)
And a note on the relative evil of comments; bad or not, well placed comments have saved me an awful lot of time when taking on maintenance of code bases in the past
Indeed. I would rather have too many comments, to the point that some are not needed, than too few, and remain confused.
C++ for the C++ness of it (Score:3)
I found both the article and what JC wrote to be highly informative and rather validating of my approach to things. In software, we usually get little validation because of the wide variety of opinions of who we work with. We've all seen the extremes: The hard core C programmer who can't be bothered with any OO nonsense, and who advocates inspecting the assembly of every method you write. The C++ hippie who sees everything as some kind of exercise in getting the compiler to write the code for you.
I'm sure most of us follow a more balanced approach. C++ has to be about performance over anything else, otherwise there are plenty of other languages that accomplish much greater degrees of expression, but can't cash the performance check. But, expressibility is important, too, because performance goes out the door once we stop understanding what the code is doing. It's nice to have a language that lets you express things somewhat functionally, yet gives you the flexibility to wring out serious performance.
lost me (Score:4, Interesting)
if this guy was interviewing here and mentioned all the things in his article, i probably wouldn't hire him. too much "religion", as it were, which is a huge red flag for me because it's usually masking something...
Re:lost me (Score:4, Insightful)
3.) tight vertical spacing is archaic and stupid, unless absolutely necessary for some display reason
After spending the first several years of my C programming life using K&R syntax, I eventually realized that many of the problems I had maintaining my code came from trying to parse through the dense insanity of tight vertical spacing (and other K&R style issues that originated from constraints that haven't existed in many years).
When reading Linux source code, the first thing I have to do in order to make the code intelligible is reformat it away from K&R. K&R is perhaps the single ugliest coding style I have ever seen or used.
Re: (Score:3)
The problem with very talented programers, is that only very talented programers can easily understand their code. I understand it can be problematic in corprate environment when the next Junior comes in and gets totally lost.
But on the other hand, I guess these guys (The guy from TFA and Carmack) write far better code (performances wise, maintenance wise, etc), than most of the people at any standard IT company.
At my job (I'm associate professor at a French university), I got to sse a lot of programming st
iD (Score:3)
Most game companies write engines to make games. The game is the product, so it's not too important how it looks under the cover. iD makes games to publicize engines. So it really does matter for the code to look nice.
BS this is how it looked during development (Score:3)
Its easy to go back over a finished codebase, run some static analysis and refactoring tools and clean it up. Chances are this is what was done before releasing it to be open source. I can guarantee this source coded didn't look anything like this during development.
Of course this is maybe why the game took longer to develop, spending more time making the code look purdy then, say, making the game a superlative gaming experience.
Fairly ugly (Score:3)
The Doom 3 code is quite ugly.
If you want to read good code, try the Linux kernel.
If that's beautiful, I really don't want to read his "ugly" code...
Comments are bad? (Score:4, Funny)
Oh my god, this is the worst programming advice I've ever heard. Is this a joke? Maybe some clever attempt at creating job security?
There is a terrible dearth of commented code in the world -- especially in the lower-level languages like C and C++ -- and this guy is telling people we need fewer comments in our code?
The things he likes are the things I hate (Score:5, Insightful)
He loves the lack of white space, I hate it. Cramped code is irritating to read. If you want to take up less vertical space, reduce your font and increase the whitespace. You have a better sense of the separation of statements, stronger scoping and less room for error.
He also loves the lack of comments. I remain firmly in the camp that if you eschew comments as common practice, you're an idiot and you should stay away from programming on big teams.
It's not a clarity of code issue. I expect your code to be clear, too. But even after 20 years of programming, I read English faster than I read code. A description of an algorithm in English is going to be more terse than the code that implements it. Your code has to account for edge cases, but I probably just want to know what the code does and how the code does it at a high level so I can get a sense of the system and architecture. A descriptive method name only tells me WHAT the method does, not the manner in which it's done.
English (any natural language, really) is a powerful language with extraordinary expressive power. I don't understand why programmers are constantly trying to sweep it under the rug. Don't fill your code with useless comments like // increments the counter by 1, but if you're doing a non-trivial mathematical calculation that takes a whole method to encapsulate it, let me know what I'm getting in to.
Code comments--especially system level comments--should include the name of the author or current maintainer, as well. I tag my methods with my name and the date that the code was put in so people know where to go if there's trouble. They don't have to hunt through perforce time-lapses to see that I checked it in, they just email me.
And have some consideration for the new guy on the team, or the team that has to use your code 5 years in the future. They can't ask you questions, the context of the situation is lost, the code-base might be in the middle of being re-purposed (common in the game industry--which is where I am); comments are essential to maintainability. Man, I do code reviews and people often manage to forget exactly what they were trying to do, and it's only been a few hours. We always work it out, but if there were a comment, we wouldn't even have to spend THAT time.
Use comments. Use them wisely. It makes you a better programmer because you're wasting less of OTHER people's time.
Disappointing analysis. (Score:3)
Fantastic article, and from Kotaku? Impressive. (Score:3)
Slightly misleading (Score:3)
Fool! Quake III Arena was also written in C.
Nice code or agrees with his style (Score:3)
if(x==1){bla();}
if(x==1){
bla();
}
if ( x==1 ){
bla();
}
if(x==1)
{
bla();
}
Are taste. Comments and variable/function names are functional and thus more arguable (but still generally religious). Any review of this sort that talks about code formatting is wasting our time(unless they went way overboard with something stupid) with religious nonsense so I wish he would stick to the benefits of how they pass parameters etc.
The only time anyone ever "Wins" the code formatting argument is when something else is brought into the argument such as "Format it my way or get fired." or "Format it my way or I quit"
Nearly every place I worked had someone who always began the argument about coding standards with "I don't care which standard we use as long as we all stick to it." But then they relentlessly argued for their standards and wouldn't give an inch with well structured arguments for every space, comma, and return. Often these standards had all kinds of specific metrics like a certain ratio of comments to lines of code. This way they could point to other people's code and mathematically prove that they sucked. Although the worst were the passive aggressive sorts who would reformat any block of code they touched on to "their" standard which was wildly different from the entire rest of the programming team.
Re: (Score:3)
In any properly written compiler, both are pretty equivalent and in almost all cases there wouldn't even be a difference in generated assembler, let alone performance.
case is basically a lot of else-if's, and else-if's are basically a single-path case.
Re: (Score:3)
As others have pointed out, case statements utilize jump tables for better performance. It is noteworthy because depending on the elements within a case statement, it isn't always efficient. If you're testing an enum then it will be great as the resulting jump table will be small. If you're testing an int value, the resulting jump table could be huge - so you have to be careful.
Depending on what you're programming for (embedded systems?) the choice of if to use a case or if-else statement is not alway
Re:Else ifs - yuck (Score:4, Insightful)
Case statements can be optimized using jump tables.
Any semantically-equivalent code (that is, two instances of code that "does the same thing") can be optimized to the same set of instructions. It's just a matter of whether or not the optimizer can figure that out.
Re: (Score:3)
Switch statements are faster if there are enough cases, because a branch table can be used. For switches with only a few case statements, a good compiler should use conditional branches, resulting in the same code as an else if, because that is faster in that case. I presume a really good compiler would also be smart enough to use a branch table if enough else ifs are chained together too, but I haven't had to deal with writing that highly optimized code for a while to have been keeping tabs on compilers
Re: (Score:2, Informative)
case statements are not faster than if-else statements. Often a case statement will be turned into a load of if-else's by the compiler anyway (and a set of if-else statements could be turned a lookup table too!)
In any case, "far faster" is not true, the machine statements generated are tiny compared to every other inefficiency in a codebase. Thinking a case statement makes your code faster is like painting your car red to improve its speed when you've got a load of heavy junk in the boot.
Re:Else ifs - yuck (Score:5, Informative)
Often as in you've measured it, or often as in "I'm making shit up"?
A good compiler will never implement a case statement as a load of if-else's, unless the case values are sparse, or you're not optimizing.
Meanwhile, transforming a set of if-else statements into a lookup table is seldom possible unless the if-elses all compare the same integer variable to a constant. In that case, it can in theory, but almost certainly won't in practice.
Other things being equal, a switch statement with contiguous constant cases will almost always compile to faster code than the equivalent set of if-elses. And it will be far faster. Every if/else induces a branch, and mis-prediction will be severe on most of those branches, causing 10-20+ cycles of stall on modern processors. The jump table mispredicts almost always, but only once. If one arm is taken 99% of the time you can speed things up by using an if/else and then a switch, but that's a rare case.
I appreciate the fact you're responding to the idiocy of the above post, but your points are as wrong as his.
Re:Else ifs - yuck (Score:4, Insightful)
case statements are not faster than if-else statements
This is one of the worst comments I've ever seen with an Informative mod on Slashdot.
Most of the time, switch / case statements are optimized by the compiler to use jump tables that are much more efficient at runtime than evaluating expression after expression.
Re:Else ifs - yuck (Score:4, Insightful)
Are you an idiot? Case statements don't do the same thing as if else. The example in the article does some floating-point compares. How do you represent that as a case statement in C++? Come on, I'm waiting. Oh, that's right. You can't.
Case statements take an integer value and switch based on it. You cannot have case (dot < -epsilon) or case (dot > epsilon). Got that? Good.
wonder what else ID missed
If you think Carmack "missed" something, take a deep breath, count to ten, and figure out what you missed.
No, he's not perfect - I found a bug in DOOM 2 that he never tracked down - but until you prove yourself STFU about how Carmack may have "missed" something you only learned on Stack Overflow anyway. Carmack is a Level 99 Wizard while all you can do is read the descriptions of the kinds of spells he can cast.
God people like you are annoying. Shut up and think, and you might learn something.
You asked for it. (Score:5, Informative)
How do you represent that as a case statement in C++? Come on, I'm waiting. Oh, that's right. You can't.
switch (dot < -LIGHT_CLIP_EPSILON ? 1 : dot > LIGHT_CLIP_EPSILON ? 2 : 0) {
case 1:
sides[i] = SIDE_BACK;
break;
case 2:
sides[i] = SIDE_FRONT;
break;
default:
sides[i] = SIDE_ON;
}
Yeah, yeah, I know, that's totally ridiculous (although I did see things as bad and worse as a CS instructor's assistant whose job it was to grade Pascal students' programming assignments back in the day - that was very interesting to say the least).
On a side note, why can't > and < characters be used in a code element? Um, that's lame, especially for a site that discusses programming so much.
Re: (Score:3)
Ow! my eye!
But technically
x ? y : u ? v : w
is just shorthand for
if (x) {y} else if (u) {v} else {w}
so your solution doesn't really solve the problem with a case statement; it solves it with if-else, and then decorates it with a redundant case statement.
And chaining the ternary operator like that? Yikes.
Re: (Score:3)
...since Clinton was in the white hose.
I don't remember that part of the Lewinski scandal.
Re: (Score:3)
Re:Else ifs - yuck (Score:5, Informative)
I know some situations else-if statements are necessary, but my understanding is that case statements are far faster.
Very often rules about efficiency like this one are incorrect. Sometimes the compiler will even change things completely when you compile it. In one example, I once carefully wrote a function to only have a return statement at the end, because I (somehow) thought it would be more efficient. Then I looked at the assembly output from the compiler, only to find that the compiler had added in all the extra return statements I had so carefully avoided. After that, I just went with what was most readable.
If you really care about efficiency, there is one way to do it: you MUST time your code. Try the case statement, and time it. Then try the if statements, and time it. If you don't time it, you are just guessing and you WILL be wrong.
The case of the if statements in the article is a tricky example, because it is a range, and writing it as a switch statement would likely be a large table. Doing this could actually slow things down because it fills up the memory caches with mostly needless information. Note this can also be a problem with traditional optimizations like pre-calculated tables or loop unrolling, they can actually slow things down.
TLDR: If you want to make your code efficient, you need to time it.
Re: (Score:3)
Re: (Score:3)
And since somebody else will say this if I don't, OO enthusiasts have a distaste for both else-if's and case statements, seeing either as a candidate for subclass
Re: (Score:3)
As many others have pointed out in their replies to you, a good optimizer will often wash away the performance differences. Performance is one of those things that is desperately needed when it's needed, but in general It's more important to me that my code be readable and provably correct. That means using the language and statements that make my intentions clear.
As far as efficiency goes, when you see an "else if" or "case" statement, consider polymorphism and a state pattern instead. You make the deci
Re: (Score:3)
Re:Solaris Code (Score:5, Interesting)
Re:Solaris Code (Score:4, Insightful)
l would agree here. I only saw some bits of it but comparing code between Linux, BSD, and Solaris that did the same thing, the Solaris stuff was definitely the easiest to understand. Linux I found to be the most obtuse in comparison. Though to be fair the code bases are so large with so many authors that some code may look great while others are awful. Solaris I think wins just from having coding styles and standards.
Re:subjective (Score:4, Informative)
> I don't see the point of not using STL.
Code bloat, hard to debug, memory fragmentation, and no way to serialize/deserialize in a fast way.
I highly recommend ALL C++ programmers to read this doc on why EA designed and implemented their own STL version. It provides insight into the type of problems console game developers have face that the PC game developers just routinely ignore or are ignorant of.
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2271.html [open-std.org]