Slashdot Mirror


Doom 3 Source Code: Beautiful

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."

399 comments

  1. Solaris Code by Anonymous Coward · · Score: 1

    ..also nice.

    1. Re:Solaris Code by Anonymous Coward · · Score: 1

      Yep, almost as nice as FreeBSDs code.

    2. Re:Solaris Code by phantomfive · · Score: 5, Interesting

      Write a review of Solaris code, and it'll probably get posted on Slashdot, too. I for one would be interested in reading that.

      --
      "First they came for the slanderers and i said nothing."
    3. Re:Solaris Code by Anonymous Coward · · Score: 0

      Oracle lawsuit in 3... 2... 1...

    4. Re:Solaris Code by Darinbob · · Score: 3, 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.

    5. Re:Solaris Code by ThePhilips · · Score: 1

      I haven't looked into Solaris code, but I have seen (with the eyes of system programmer) both BSD and Linux code.

      BSD is much more readable - but in larger part because it is much simpler.

      But Linux is also readable - if you know how the stuff works. The modularity of the kernel also has an impact, since in a place where BSD has a single readable function, in Linux one might find piece of code with calls to potentially dynamically loaded modules. But that is still the simplest part. Hard part is the "how the stuff works." Linux for performance reasons has many things implemented up-side-down and it takes some time to get used to it.

      Over the life time of Linux, there were many discussion about the readability vs. performance. In the beginning readability was mostly winning. But as Linux became more and more popular, later literally de facto server OS, the choice (IIRC Linus was also involved in the discussion) was inevitably falling to the performance. It ended up with something like: few CPU cycles saved in one function, multiplied by million of Linux boxes, equals millions of cycles saved.

      BSDs IMO always more cared about feature completeness and long-term maintainability. That I believe led to simpler and more readable code. (By contrast, Linux culture treats code as replaceable and doesn't shy of major rewrites/throwing away old code when needed, because there are more Linux kernel developers than the kernel itself. In BSD world that generally leads to hurt pride and another (short-lived) BSD fork - in Linux it is a daily routine.)

      --
      All hope abandon ye who enter here.
    6. Re:Solaris Code by torroid · · Score: 1

      You don't need to post source or comment on it to start a lawsuit. You just need to mention Oracle.

  2. Beautiful code but by discord5 · · Score: 5, Funny
    • It might be beautiful code, but 90% of it just renders a black screen in a horribly inefficient way.
    • For best effect the source code should be read in the dark with a flashlight in your hand.
    • // TODO : add the code for the lightswitch in this class

    I'll be here all week.

    1. Re:Beautiful code but by djlemma · · Score: 4, Funny

      Don't forget that you can't use your keyboard and your flashlight at the same time...

    2. Re:Beautiful code but by Anonymous Coward · · Score: 1

      maybe you should buy display that can do proper black levels...

    3. Re:Beautiful code but by Anonymous Coward · · Score: 0

      You have not played the BFG Edition, have you?

    4. Re:Beautiful code but by IcyNeko · · 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!"

    5. Re:Beautiful code but by PPalmgren · · Score: 2

      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.

    6. Re:Beautiful code but by Stormwatch · · 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.

    7. Re:Beautiful code but by Anonymous Coward · · Score: 0

      Funny, but true. I remember spending hours tweaking the config file to get the frame-rates somewhere near acceptable. Even on modern hardware, it lags and jitters unacceptably. Beautiful code it may have been... but optimized for actual functionality, it was not.

    8. Re:Beautiful code but by Joehonkie · · Score: 1

      Yes, Romero and McGee have a GREAT track record these days...

    9. Re:Beautiful code but by gl4ss · · Score: 2

      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.

      --
      world was created 5 seconds before this post as it is.
    10. Re:Beautiful code but by meerling · · Score: 2

      You can have it fast, cheap, or good, but you can't have all three, and now you want me to add beautiful to the list?
      You really don't get it, do you... :D

    11. Re:Beautiful code but by Stormwatch · · Score: 2

      Daikatana and Alice were far from perfect, but they're still more enjoyable than Doom 3.

    12. Re:Beautiful code but by dpilot · · Score: 0, Offtopic

      Oh come on... The duct-tape patch is old news.

      --
      The living have better things to do than to continue hating the dead.
    13. Re:Beautiful code but by NatasRevol · · Score: 2

      So we can still only have 2?

      --
      There are two types of people in the world: Those who crave closure
    14. Re:Beautiful code but by binarylarry · · Score: 1

      Oh I'll never forget the wonderful score Prince did for Doom 2.

      --
      Mod me down, my New Earth Global Warmingist friends!
    15. Re:Beautiful code but by Anonymous Coward · · Score: 0

      Pretty sure both sales and critics (on average) disagree with that.

    16. Re:Beautiful code but by Anonymous Coward · · Score: 1

      It's a fair dig if you had to play the whole damned game through wtihout the duct tape patch.

    17. Re:Beautiful code but by Anonymous Coward · · Score: 5, Insightful

      I did. No issues. Hint: The dark parts are supposed to be dark.

    18. Re:Beautiful code but by X0563511 · · Score: 1

      I found it to be stressful, in a fun way, having to manage that clunky shitty flashlight like that. I'm sorry not everyone thinks that kind of thing is fun.

      --
      For large sets, this will be our guide even unto death, for the LORD will work for each type of data it is applied to...
    19. Re:Beautiful code but by gman003 · · Score: 2

      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.

    20. Re:Beautiful code but by X0563511 · · Score: 4, 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.

      --
      For large sets, this will be our guide even unto death, for the LORD will work for each type of data it is applied to...
    21. Re:Beautiful code but by Anonymous Coward · · Score: 0

      As someone who played Alice (bought for sister), Daikatana (It was cheap and infamous!), and Doom 3, I can tell you that out of the three of them Alice was by far the better story, art, and action. Doom3 had quite a bit more of the shiny (Alice was Tech3, Dai Tech 2, and Doom obv Tech 4), but as far as gameplay, performance, and enjoyment went it was like maybe a 3, Daikatana was like a 1, and Alice was like an 8 (There's better games but it was pretty high up the list.)

      Still haven't gotten a chance to play the new Alice sequel however, anybody else got a review?

    22. Re:Beautiful code but by Anonymous Coward · · Score: 0

      The original Alice has an 85 and 8.6 user score on Metacritic, its sequel has 75 and an 8.6 user score. Doom 3 has 87 and 7.3 user score, with BFG edition getting worse scores (59 and 4.4).
      I'll give you sales, though; Doom 3 moved who gives a damn about sales units, which is more than both Alice games combined (at CoD moves millions of games units sold, and mass appeal and advertising does not equal quality units sold, respectively.)

    23. Re:Beautiful code but by djlemma · · Score: 2

      True, although I liked Doom3 without the patch. It was a cool extra challenge, it enhanced the mood, and it made sure you could see the neat lighting effects made by the various projectiles being thrown at you.

      I think the patch for using flashlight and keyboard simultaneously would be something like "headlamp" or "teeth" instead of duct tape, though. :)

    24. Re:Beautiful code but by Anonymous Coward · · Score: 2, Informative

      John Carmack actually commented on the article saying that the code wasn't that good.

    25. Re:Beautiful code but by Anonymous Coward · · Score: 0

      I just checked - Alice and Doom 3 had roughly the same scores in reviews.

    26. Re:Beautiful code but by RatBastard · · Score: 1

      It was the "every fourth door ambush" crap that got to me. It was like you could sense when you were going to get jumped from behind when you went through some doors. I started walking into rooms backwards and taking out the ambushes every third or fourth door. I got as far as the Delta Lab before just losing interest.

      And let's not even talk about the utter shitpile that is Rage.

      --
      Boobies never hurt anyone. - Sherry Glaser.
    27. Re:Beautiful code but by gman003 · · Score: 1

      Actually, I played Rage all the way through - I think it's the best game id has made since Quake ][, or maybe Q3. The shooting is fun, the driving is fun, and the game looks amazing. The story was even tolerable, with the exception of the ending.

    28. Re:Beautiful code but by girlintraining · · Score: 2

      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.

      --
      #fuckbeta #iamslashdot #dicemustdie
    29. Re:Beautiful code but by DrXym · · Score: 4, Insightful

      The dark parts are dark because the game was completely bereft of ways to generate suspense or fear. Typical Doom 3 level - walk forward, lights out, invisible panel opens, bang bang bang, lights on, advance a bit, lights out, invisible panel opens, bang bang bang, lights on. It was scary the first time, after the 20th time it was just boring especially as the game was almost totally linear. FEAR suffered exactly the same issue.

    30. Re:Beautiful code but by Gr8Apes · · Score: 2

      It was so boringly repetitious that I, along with many others, wished to return our copies of Doom 3 for a refund. I have no idea how far into the game I got, nor how far left to go, but the lack of fun as you plodded through the same setup every 10-15 steps must have killed off multiple IQ points for those that continued...

      --
      The cesspool just got a check and balance.
    31. Re:Beautiful code but by mfnickster · · Score: 1

      It was mostly the repetition, the constant stuff jumping at you. It's a very fatiguing game

      Yeah, I felt that way too. I was surprised that after the success of Halo, ID came up with such a mind-numbingly linear game in terms of settings and gameplay.

      Halo also suffers from the "repeat-this-level-until-you-get-it-right-and-advance" problem, but the settings were fantastic (if repetitious) and had a lot of variety. You also had much more freedom to play around in the space, drive different vehicles, etc.

      I still play Battlefield 1942 regularly just because it offers almost total freedom of action on the game field and the battles play out differently every single time!

      --
      "Slow down, Cowboy! It has been 3 years, 7 months and 26 days since you last successfully posted a comment."
    32. Re:Beautiful code but by RoboRay · · Score: 1

      The complete lack of any thought put into entertaining gameplay for Doom3 makes it hard for me to be interested in the underlying code.

    33. Re:Beautiful code but by Narot23 · · Score: 1

      The flashlight issue peeved everyone, but the most annoying part of the game (in my experience) was the "monster closets". That felt like a very dated mechanic and ruined the atmosphere.

    34. Re:Beautiful code but by Stormwatch · · Score: 1

      There's a trick to play without them.

    35. Re:Beautiful code but by Dan667 · · Score: 1

      yea, I liked it too. Scared the crap out of me.

    36. Re:Beautiful code but by Ash+Vince · · 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.

      --
      I dont read /. to RTFA, I read /. to offend people in ignorance.
    37. Re:Beautiful code but by wierd_w · · Score: 1

      Lots of eyecandy. More mature story (as in, sexual theme content), irritating retcons.

      Gameplay has lots of smashing, especially if you use the hobbyhorse attacks. (:D) minigames are repetitious.

      Seemed more like artistic masterbation on the part of the character design artists. (Alice literally has a different outfit and hairstyle for each "world" of wonderland.)

      Alice was harder, and grittier as a character in McGee's, much less so in the SpicyHorse made sequel.

      Game has less replay value than the first one. Game *does* come with the original game as a DLC though, so you can play it on the console. Hard to use the thrown attack of the kife without the precision of the mouse however.

      It was worth the download for the first playthrough and the eyecandy. Haven't played it again though.

    38. Re: Beautiful code but by davesag · · Score: 1

      Agreed. Peterson was ex Chaosium and knew how to design games. Doom 2 was way better than Doom 3. That game infected my dreams back in the 1990s

      --
      I used to have a better sig than this, but I got tired of it
    39. Re:Beautiful code but by flayzernax · · Score: 1

      It was no problem. It was pretty fun, I never patched my version of doom 3.

      Played in darkened room alone at night with good stereo audio.

    40. Re:Beautiful code but by flayzernax · · Score: 3, 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.

    41. Re:Beautiful code but by flayzernax · · Score: 2

      It was better then Uwe Bolls movies.

    42. Re:Beautiful code but by wiggles · · Score: 4, 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.

    43. Re:Beautiful code but by Trax3001BBS · · Score: 3, 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!

    44. Re:Beautiful code but by tibit · · Score: 1

      I always think that computer games are like books: you fill in the blanks with your own imagination. I find that many people who complain like you do, turn out, once I get to know them, to be dullards. YMMV. Yes, of course the gameplay may be repetituous, but every FPS I've tried so far is like that. I still enjoy them.

      --
      A successful API design takes a mixture of software design and pedagogy.
    45. Re:Beautiful code but by Anonymous Coward · · Score: 0

      That's what the muzzle flash is for. Plasma bolts for the really dark areas.

    46. Re:Beautiful code but by Gr8Apes · · Score: 1

      I find generally that people that enjoy mindlessly repetitious games with no strategic component (IOW, monster falls from ceiling, shoot twice with shotgun, point right, shoot twice to hit monster behind panel, reload, move forward 10-15 steps until next ceiling panel appears) to be uniquely lacking in imagination and have an amazingly lack of creative potential. Naturally, YMMV, and you also enjoy knitting because you like sweaters.

      --
      The cesspool just got a check and balance.
    47. Re:Beautiful code but by Stormwatch · · Score: 2

      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.

    48. Re:Beautiful code but by Tarlus · · Score: 1

      and had a lot of variety

      If you consider palette swaps to be variety...

      --
      /* No Comment */
    49. Re:Beautiful code but by Anonymous Coward · · Score: 1

      Halo was a mind-numbingly linear as well. More so with the halflife series.

      Now the best non-linear game play has to be Deus Ex. The only problem was the story was essentially linear. It would have been a perfect game if your choices throughout the same affected the outcome of the story.

    50. Re:Beautiful code but by gl4ss · · Score: 1

      I played it without the patch. it was doable, but it was a friggin bad design decision.

      HOWEVER... I wondered afterwards why the fuck I bothered. the game sucks ass as it shipped. it was supposed to be like it was, but that was just ASS. cheapest, laziest horror design fucking ever, teleporting enemies right behind your back all the fucking time. the level design was just lazy and downright insulting.

      sad part? I'm going to play it again when oculus gets around to shipping their goggles..

      --
      world was created 5 seconds before this post as it is.
    51. Re:Beautiful code but by gl4ss · · Score: 1

      rage looks worse than quake4/doom3(things are just pasted on walls, gigafigatextures ftw!)... q4 I liked a lot, but then again it's just id's engine.

      it's sort of ok tech demo of 2 levels.

      --
      world was created 5 seconds before this post as it is.
    52. Re:Beautiful code but by gl4ss · · Score: 1

      what stress? when it's certain you're going to get a teleport(or opening door) scare it's no longer a scare. it's just certain, it's just how the game works. you go into rooms and every third corner on the hallways something is going to teleport behind you and long enough dark portions always have enemies, because otherwise why add the hallway at all, right? to add beliviability to the stations layout, to make it into an adventure? why the fuck bother when we can just add closets full of zombies!

      it was just too good at making you not want to play it at all. doom1 did the teleport enemies behind back trick couple of times too but it was never used so cheaply.

      what do I want from a space station fps with PDA's as per story?? system shock. they would have done well to study the use of light/shadows in shock too.

      --
      world was created 5 seconds before this post as it is.
    53. Re:Beautiful code but by Stormwatch · · Score: 1

      Rage was a nice half of a game. It was clearly incomplete. There are some areas, like the crater and the swamp, that make you feel something obviously should happen there, but nothing does. And yes, there's that sudden, unfulfilling ending.

    54. Re:Beautiful code but by mfnickster · · Score: 1

      If you consider palette swaps to be variety...

      No, I meant the map designs. There were wide-open grassy valleys, tight underground passages, caves, towers, bridges, ship corridors, snow-covered canyons. A hell of a lot of work went into designing that world.

      --
      "Slow down, Cowboy! It has been 3 years, 7 months and 26 days since you last successfully posted a comment."
    55. Re:Beautiful code but by Anonymous Coward · · Score: 0

      Doom 3 was pretty but got old real quick. It's dark but I have a flashlight that is annoying to use. Oh, I walked into a new room. I bet these little invisible doors to meaningless rooms will pop open behind me and monsters will come out. Then while I'm turned around fighting them some will come up behind me. Repeat forever.

    56. Re:Beautiful code but by Anonymous Coward · · Score: 0

      Yeah...and you've also got the advantage of living in your parents' basement so that you don't have to worry about any other pesky light sources.

    57. Re:Beautiful code but by Anonymous Coward · · Score: 1

      Breaking the Doom 3 CD in half and using the jagged edge to castrate yourself is better than watching an Uwe Boll movie.

    58. Re:Beautiful code but by hairyfeet · · Score: 1

      I don't know why that was labeled funny, should have gotten insightful. When you look at what its system reqs are VS what its actually rendering and then compare it to the latest Unreal or Source engines its just not that great folks.

      I've seen Doom 3 get a case of "the chugs" when a scene gets hectic but when you look at what is going on in the scene other than a few lighting effects its just not doing that much, certainly not enough to get a case of the chugs. The Doom 3 engine always reminds me of the CryEngine in that way, sure you can get a pretty nice scene made by using it but it'll suck more resources and will be more likely to bog than the Unreal and Source engine games even when doing less on screen than those 2.

      There is a reason why everybody used Unreal engines all these years and the ID Tech 4 never got used for much of anything folks, its just not a great engine.

      --
      ACs don't waste your time replying, your posts are never seen by me.
    59. Re:Beautiful code but by Tagged_84 · · Score: 2

      Yes because gameplay is a reflection on the game's underlying code. Judging by your comment it's unlikely you would be able to, or even have had the desire to, read the code in the first place.

    60. Re:Beautiful code but by Anonymous Coward · · Score: 0

      You're wrong. I hope most Doomheads that originated from the beginning like I did can appreciate Action Doom II. http://action.mancubus.net/

      A fucking masterpiece.

      Play it.

    61. Re:Beautiful code but by Tagged_84 · · Score: 2

      Err you "played" it but quit before the first level!?.. Well I played Daikatana to completion, also Doom 3, and both were fun games. I found Daikatana to be a much stronger design hampered by technical issues, while Doom 3 lacked such a strong design but had a very smooth base. Both games I completed over the course of a couple days of constant playing, perhaps FPS isn't your cup of tea?

    62. Re:Beautiful code but by Anonymous Coward · · Score: 0

      It might be more immersive with goggles hehe, but I was pretty bored with it other then a few suspenseful parts. Playability does not = fun. Classic Doom was more fun in that regard.

      Now, if there was a way to pick up the pace of gameplay, more monsters, higher damage weapons, and easier to die. That might make it a bit more interesting.

    63. Re:Beautiful code but by flayzernax · · Score: 1

      LOL ;p

      I was wasted drunk when I saw the Doommovie in the theater. So I survived. The Rock for some reason also has a calming effect for me in movies. Its the one thing they got right.

    64. Re:Beautiful code but by RoboRay · · Score: 0

      You can stick your snotty remarks right back up in your ass.

    65. Re:Beautiful code but by Tagged_84 · · Score: 1

      Someone's on their rags.... What it's ok for your to criticize but if someone does it back it's totally unfair?

    66. Re:Beautiful code but by v1 · · Score: 1

      Now the best non-linear game play has to be Deus Ex

      I'd have to agree with that. It had good replayability also because you had so many binary upgrade decisions to make. And most levels could be solved with at least two distinct play styles. (stealth and power)

      It was also refreshing to have three factions fighting for your loyalty instead of the usual two found in other games that play that way.

      --
      I work for the Department of Redundancy Department.
    67. Re:Beautiful code but by RoboRay · · Score: 1

      An insult is not simple criticism. Perhaps you are not able to comprehend your own words.

    68. Re:Beautiful code but by Tagged_84 · · Score: 1

      I'm simply trying to point out that what you said lacks technical sense to those genuinely interested in programming. Gameplay and code do not directly relate to each other and your comment implied they did. Maybe I came off harsh, but that's me, no different to how I speak away from the keyboard, hardly an insult worthy of anything.

      If you want to be picky I find "The complete lack of any thought" is more of an insult than criticism. A critic shouldn't contain assumptions, more along the lines of "The apparently lack of.."

    69. Re:Beautiful code but by RoboRay · · Score: 1

      Fair enough, and point taken. But perhaps a reference to my interest rather than my ability would have been more in order and made your point just as well. Quite possibly better.

    70. Re:Beautiful code but by shutdown+-p+now · · Score: 1

      It's the job of the game designer to make a game where it's easy to fill the blanks, though.

      Doom 3 made it extremely tedious.

    71. Re:Beautiful code but by Anonymous Coward · · Score: 0

      Oh no... Its the Revenge Of The Pod People

    72. Re:Beautiful code but by Anonymous Coward · · Score: 0

      Or not... Oops sorry...just reread the review and it's offensive

    73. Re:Beautiful code but by Anonymous Coward · · Score: 0

      Please don't set Romero and McGee on the same level. McGee has done several decent games, even if they might not be to everyone's taste. He also has the balls to try pretty whack stuff from time to time. Daikatana on the other hand (and yes I played through all of it), suffered from lots of things but most of all, ironically, from bad design decisions.
      It's fascinating that all of them; Doom 3 (and I would also add Quake 2), Daikatana and Alice games all suffer from having a too high ratio of levels relative to interesting events in the levels. They would all benefit by (gasp!) making it into a shorter, more condensed interesting experience. But maybe that's just my opinion.

    74. Re:Beautiful code but by Psyborgue · · Score: 1

      They added a similar patch into the BFG edition and you can't turn it off, which is one reason the re-release got lower ratings. I, too, liked Doom 3 when you had to switch between flashlight and your gun. It gave you a sense of being insufficiently armed and heightened the tension.

    75. Re:Beautiful code but by Psyborgue · · Score: 1

      I think a lot of people enjoyed it, myself included. It's a pity you can't switch it back to the old way in the BFG edition (re-release).

    76. Re:Beautiful code but by Ash+Vince · · Score: 1

      what stress? when it's certain you're going to get a teleport(or opening door) scare it's no longer a scare. it's just certain, it's just how the game works. you go into rooms and every third corner on the hallways something is going to teleport behind you and long enough dark portions always have enemies, because otherwise why add the hallway at all, right? to add beliviability to the stations layout, to make it into an adventure? why the fuck bother when we can just add closets full of zombies!

      it was just too good at making you not want to play it at all. doom1 did the teleport enemies behind back trick couple of times too but it was never used so cheaply.

      what do I want from a space station fps with PDA's as per story?? system shock. they would have done well to study the use of light/shadows in shock too.

      The stress I meant was the generally confined spaces, but your right as well that they did seem to overuse the teleporting in monster trick.

      --
      I dont read /. to RTFA, I read /. to offend people in ignorance.
    77. Re:Beautiful code but by ardor · · Score: 1

      There is a reason why everybody used Unreal engines all these years and the ID Tech 4 never got used for much of anything folks, its just not a great engine.

      I tend to agree. There as a lot of "emperor's new clothes" going on with ID Tech 4, in that nobody wanted to admit that it underperformed. However, I think the main reason is that it was written at a time when shaders just got introduced, and the whole state of realtime 3D graphics was in heavy flux. As a result, it has several code paths specialized for GPU architectures that don't exist anymore. Nowadays, shader languages and APIs have stabilized, and the bottlenecks are in entirely different places. Note that Unreal Engine 3 was released several years after ID Tech 4, thus benefitting from more matured APIs.

      Although I think the main selling point of UE3 over ID Tech 4 was the excellent toolchain. People tend to forget that with engines, the *actual* value lies in the toolchain. This is also where open source engines routinely fail; know any with a toolchain that can rival the UDK?

      --
      This sig does not contain any SCO code.
    78. Re:Beautiful code but by Anonymous Coward · · Score: 0

      It's like they forgot that doom 1 was a fast paced action game. Instead they went for horror and thrills, which ende dup being a small closet full of monsters every 20 yards.

    79. Re:Beautiful code but by DrXym · · Score: 1
      FEAR certainly had a more advanced game engine than DOOM and AI but it was undermined by levels which bordered on the generic - office corridors, warehouse docks, rooftops, a pathetically derivative horror story which I found neither scary or interesting, and the same linearity as Doom 3 which encourages the same advance, trigger, fight, save, advance, trigger, fight save mentality. DOOM 3 had a good engine for its day but I didn't think it was put to good use. Far Cry was a far more impressive game by miles (despite its generic plot and some crappy cutscenes) which is shocking considering the pedigree of Id at the time.

      DOOM 3 and FEAR (and Bioshock) also used one of the laziest forms of story telling there is - the expository voice mail / message / tape recording conveniently placed around on levels. That cliche really needs to die but it's still being used in some games.

    80. Re:Beautiful code but by djlemma · · Score: 1

      As a counterpoint (from your own link) there's this page.....

    81. Re:Beautiful code but by znanue · · Score: 1

      D3, at the time, easily had the most beautiful dynamic lighting of anything out there. I'm not sure that its fair to claim that it was underperforming for what it was doing at the time that it was doing it.

      Z

    82. Re:Beautiful code but by Anonymous Coward · · Score: 0

      It was better then Uwe Bolls movies.

      Isn't 'X is better than an Uwe Boll movie' a canonical example of a tautology?

    83. Re:Beautiful code but by hairyfeet · · Score: 1

      But what good is that if its shitting resources and chugging? Again there is A REASON why damned near every game out there is powered by Unreal while ID Tech like the Cryengine is pretty much only used by the parent company, and that is because it sucks.

      Having pretty lighting is worth exactly fuck and all if you chug when you try to put anything under that lighting and that is ID Tech 4 in a nutshell. Again just like the Cryengine it can make a STATIC scene that is picture postcard pretty, but have some action going on and watch it slam the living shit out of the resources. I've seen games that looked a hell of a lot better than Doom 3 that used a hell of a lot less resources to do so, of course they were all running Unreal, nobody used the ID Tech 4 because it just wasn't any good.

      Of course the sad part is making this engine open source won't do squat, because we have all seen what a new open sourced engine means...another 50 CTF Q3 Arena rip offs...yay. Just what the world needs, another MP only CTF DM game...yawn. Wake me up when you get a 3D shooter that is FOSS with an actual engaging story and a decent single player, until then you can just keep the Q3 Arena clones, thanks anyway.

      --
      ACs don't waste your time replying, your posts are never seen by me.
    84. Re:Beautiful code but by znanue · · Score: 1

      You say its worth exactly fuck. I say I found it intensely interesting experience and I wasn't alone. A game doesn't have to be popular with the majority of players for it to be popular. It wasn't the best engine, it wasn't the worst. But, it did something really well in a beautiful way, and that is remarkable (ie, worth remarking upon).

      Z

    85. Re:Beautiful code but by Anonymous Coward · · Score: 0

      This was a game mechanic they purposefully decided on. It has nothing to do with fast, cheap or good.

      Problem with ID is they were still making AAA games on tiny teams and creating all the assets and levels in the last year of production(keeps the assets from looking behind the curve and saves a huge amount of time from having to redo them as the engine and technology matures). They spend 3 - 5 years working on the technology and then shit a game with in the last year and a half of that game. They don't plan or playtest deeper mechanics for the game because of their ship cycle. They did the same thing with Rage.

      It's was last year that Carmack acknowledged that they really needed to change how they were producing games as it was hurting their company.

    86. Re:Beautiful code but by hairyfeet · · Score: 1

      But what good is crapping resources when you can get the exact same or better for less? That is like saying "I don't give a fuck if this car gets 2 MPG and doesn't do a damned thing that the car that gets 35 MPG does, because its pretty". While you are entitled to that opinion that doesn't make it insightful or even a good idea because frankly I wouldn't be surprised if you could take the unreal SDK and replicate a scene from Doom 3 with it and run TWO of those in the same CPU and memory space that Doom 3 uses.

      And sadly the state of FOSS gaming is like a bad joke, thanks to the ONLY way you can make any money in FOSS is the "blessed three" of support contracts, selling hardware, or holding out a tin cup honestly its just...well kinda sad really. In the "real" gaming world we are seeing great story lines, with great acting and directing, incredible visuals, just a great experience all around in the FOSS world the ONLY thing you EVER see from these engines being released is yet another 50 Q3 Arena ripoffs, just the same tired and lame ass modes all over again, king of the hill, CTF, DM, hell the players that want that kind of gameplay have TF2 for free where at least you have funny little back-stories and characters.

      I mean what are you gonna entice people with? Here is another copy of a decade old Q3 Arena? Tux Racer? Wesnoth which looks like if you loaded it onto a cart it would play on the SNES without even stressing the weak ass SNES CPU? This is kind of a microcosm of the weakness of FOSS in general as the ONLY thing you have to offer is "free as in beer and freedom" which players can get the former a HELL of a lot better on Windows with the FTP model and nobody gives two shits about the latter, see the lines around the block to get the latest iToy as an example. What FOSS needs is their own Bioshock or WoW but because throwing some skins on the same tired old game modes is easy while making something worth playing is fucking insanely hard all we get is the former and NEVER the latter. Kinda sad really but I have been saying for ages that thanks to the blessed three FOSS ends up like the old USSR where the only thing it has really in its favor is politics that most just don't care about, not enough to put up with poor substandard games.

      --
      ACs don't waste your time replying, your posts are never seen by me.
  3. Not the best analysis by hugortega · · Score: 3, Interesting

    It's just a personal point of view about coding style... some things like vertical spacing using the braces (at the section "Doom does not waste vertical space") are just the opposite of a readable source code (just in my opinion, of course, as someone that makes a lot of source code reviews of other people)

    1. Re:Not the best analysis by gbjbaanb · · 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.

    2. Re:Not the best analysis by Rhacman · · Score: 5, Insightful

      This is one of those topics of an almost religious fanatacism but I tend to agree. I want my braces to match in the same column and have an easier time looking at code with vertical spaces between blocks of related operations. Functions should still be short enough that they fit on a modern screen (with rare exceptions).

      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.

      --
      Account -> Discussions -> Disable Sigs
    3. Re:Not the best analysis by Anonymous Coward · · Score: 1

      Agreed on the vertical space. His justification of removing vertical space is that you can read more on a monitor, and therefore see how the function your reading fits in its surroundings - this is bogus for anything but trivial code, where the definition of a function and its uses aren't going to fit on one screen height.

    4. Re:Not the best analysis by Fallingcow · · Score: 1

      Yeah, I saw those examples in reverse-order as far as readability. I usually agree about including optional braces, but in that example the bracketless one was very eye-friendly IMO, while the one with minimal line breaks seemed like it would be headache inducing if I had to look at that kind of thing all day.

    5. Re:Not the best analysis by JaredOfEuropa · · Score: 1

      My rule for commenting stuff is: add a comment if things are not clear at first glance. This applies to everything: a class definition, function/method parameters, or code snippets. Even CSS (when fixing browser specific quirks).

      As for the rest, the Quake 3 coding standards as described in the article seem fairly common. My code looks like that, though I wouldn't call it beautiful; I'm more of a hacker than a coder. What makes code beautiful (i.e. readable) for me is a solid data and object model, and sensible (intuitive) object methods. Get this right and you can screw around with braces all you like.

      --
      If construction was anything like programming, an incorrectly fitted lock would bring down the entire building...
    6. Re:Not the best analysis by shoor · · Score: 2

      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)
                {
                          break;
                } /* end if 1==x */
                misc code

      } /* end forever */

      --
      In theory, theory and practice are the same; in practice they're different. (Yogi Berra & A. Einstein)
    7. Re:Not the best analysis by maxwell+demon · · Score: 1

      I agree. If you don't see enough vertical code, get rid of your old 14" screen.

      --
      The Tao of math: The numbers you can count are not the real numbers.
    8. Re:Not the best analysis by Darinbob · · Score: 2

      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 statements, or adding an extra comment just to separate body from conditional, or adding extra indent to the second conditional line. Of course someone may say that if a conditional line is that long that something is broken but it's very hard to avoid.

      But overall this is really just style and personal preference. Do what your organization does and live with it.

    9. Re:Not the best analysis by Darinbob · · Score: 2

      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 comments should say things like "wait for packet to be sent before changing frequency" because that's not obvious, but not things like "this waits for packet to be sent" since that should be obvious.

    10. Re:Not the best analysis by DeadCatX2 · · Score: 4, 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.

      --
      :(){ :|:& };:
    11. Re:Not the best analysis by hermitdev · · 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 should be hammered home is: tell us not *what* happens, but *why* it happens.

      The reason I like the open & close braces, with proper indentation, is that at a glance I can see where the block starts and ends. If you cannot see the start of the block and the end at the same time, the block is too large and should be refactored such that you can.

    12. Re:Not the best analysis by plover · · Score: 3, Interesting

      I noticed in their standards doc that they said all classes must start with "id". Classic Smurf naming convention.

      --
      John
    13. Re:Not the best analysis by plover · · Score: 1

      I recommend writing the unit test first, describing the inputs with explanatory names (no magic numbers allowed!) and expectations in terms of assertions. Then write your code. Now you have a readable document that exactly describes how to call your code, provides a working example, and proves your code does exactly what you say it does. Explanatory comments are a lot less needed in this world.

      --
      John
    14. Re:Not the best analysis by shoor · · Score: 1

      Well, it's hard to show in a simple example, but the main thing is the comment after the '}', to give a quick recognition of what's just finished. Good code shouldn't have too many nested braces, but even so, a block can get pretty long sometimes. The /* forever */ after the 'for(;;)' was mainly to help identify the start when you see the '} /* end forever */ at the end. Same with the /* end if 1== x */ which was pretty contrived I'll admit. It's also true that if somebody changed it to '2==x' you'd be in trouble. In real code you'd declare a constant and have something like:

      if (BREAK_CONDITION == x)

      --
      In theory, theory and practice are the same; in practice they're different. (Yogi Berra & A. Einstein)
    15. Re:Not the best analysis by AmiMoJo · · Score: 1

      Editors could make blocks and matching brackets much easier to see by simply changing the background colour between the braces. A bit like quote highlighting in email clients, but using background colours since we already have foreground colour syntax highlighting. Colours would have to be subtle.

      --
      const int one = 65536; (Silvermoon, Texture.cs)
      SJW, n: "Someone I don't like, and by the way I'm a fuckwit" - AC
    16. Re:Not the best analysis by AmiMoJo · · Score: 1

      Agreed. In TFA the author argues that a comment describing what a function takes as input and produces as output is redundant because you can just look at the function definition, but when you are trying to get a grip on someone else's code a quick explanation is just what you want.

      Comments provide a different level view of the code, giving you an overview that the code itself won't.

      --
      const int one = 65536; (Silvermoon, Texture.cs)
      SJW, n: "Someone I don't like, and by the way I'm a fuckwit" - AC
    17. Re:Not the best analysis by unity · · Score: 1

      I do the exact same thing sometimes, its saved me a crapload of debug time on tired eyes months/years later.

    18. Re:Not the best analysis by Anonymous Coward · · Score: 0

      // Yes, that's pretty ugly
      if ( (expression == too_long && convoluted) ||
          indentation.feels(unwieldy) ) {
          printf("Oh noes!");
      }

      // But this is not so bad, right?
      bool badIndent = indentation.feels(unwieldy);
      bool badExpr = expression == too_long && convoluted;
      if (badIndent || badExpr) {
          printf("Oh noes!");
      }

    19. Re:Not the best analysis by shutdown+-p+now · · Score: 1

      I think the more clear-cut example of personal style is his endorsement of the horrible, eye-melting way to "align" function declarations
      (it's still personal preference, of course, but I think enough people will agree with me about it being ugly to see the point)

    20. Re:Not the best analysis by shutdown+-p+now · · Score: 1

      Just drawing vertical lines to indicate indent levels makes it much, much easier to see the blocks (which is probably why most Python IDEs do it by default).

      But, yes, it's better with color. And such things already exist.

    21. Re:Not the best analysis by shutdown+-p+now · · Score: 1

      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.

      And why not?

      Having lengthy-but-descriptive variable and function names has one nice advantage over comments - it forces all people who muck around with that code to use that name whenever they refer to variable/function, thereby retaining its descriptiveness at points of use.

    22. Re:Not the best analysis by shutdown+-p+now · · Score: 1

      I recommend writing the contract for the function first - inputs and outputs. Of course, this implies that you need to use a language that supports Design by Contract.

      A properly written contract does the same thing that trivial unit tests (which is 90% of them) do, and does it better.

    23. Re:Not the best analysis by dkf · · Score: 1

      Having lengthy-but-descriptive variable and function names has one nice advantage over comments - it forces all people who muck around with that code to use that name whenever they refer to variable/function, thereby retaining its descriptiveness at points of use.

      You wait until you come across code where people use that long-named function all over the place for purposes other than its name characterizes. (Double points if it is never used for its original purpose any more at all!) At that point, the name has ceased to be a good thing, and become an active hinderance.

      Write the name to be useful to the consumers of the code, not the maintainer of the code.

      --
      "Little does he know, but there is no 'I' in 'Idiot'!"
    24. Re:Not the best analysis by coolmadsi · · Score: 1

      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.

      I've done similar comments before, although more like this:

      if(condition)
      {
        doSomething();
      }// else do nothing because XYZ reason

      Usually if there isn't an else because it is not needed, I explain why it isn't needed if it isn't clear from just the code. It is also helpful if there are many nested brackets that all end one after another

    25. Re:Not the best analysis by Anonymous Coward · · Score: 0

      That's because you're a C# leftover from the Delphi days.

    26. Re:Not the best analysis by shutdown+-p+now · · Score: 1

      You wait until you come across code where people use that long-named function all over the place for purposes other than its name characterizes. (Double points if it is never used for its original purpose any more at all!) At that point, the name has ceased to be a good thing, and become an active hinderance.

      I once worked on a code base where functions had names like "HeavyMetalIsFun". It's certainly not fun to maintain, but I was specifically talking about long descriptive names. Comments can be long-winded yet utterly useless, too.

      Write the name to be useful to the consumers of the code, not the maintainer of the code.

      What, exactly, would be the use of the name of a private function or a local variable to the consumers of the API?

    27. Re:Not the best analysis by Anonymous Coward · · Score: 0

      Here's just the latest in an ongoing series of horror stories about long-winded method/function names on The Daily WTF:

      http://thedailywtf.com/Articles/Self-Documenting.aspx

    28. Re:Not the best analysis by taskiss · · Score: 1

      I wrote code for nuclear weapons and that was a requirement...not only did you write the comments, they were reviewed and approved before I could actually compile code. It was part of a method that was called PDL.
      http://en.wikipedia.org/wiki/Program_Design_Language

      --
      - real hackers don't have sigs -
    29. Re:Not the best analysis by Anonymous Coward · · Score: 0

      That's what I do and it usually works quite well for me.

    30. Re:Not the best analysis by Anonymous Coward · · Score: 0

      That's the way I do it!

  4. Limiting your market by tepples · · Score: 4, Insightful

    A developer needs to make an application for the hardware people have, not the hardware he wishes people had. Otherwise, he's likely to end up limiting his market to a subset that's not big enough to turn a profit.

    1. Re:Limiting your market by Anonymous Coward · · Score: 0

      yeah people used to have CRT:s that are known for good blacklevels but upon retardation they insist buying shitty 6-bit tn panels that were not able to do blacks at all or brights and then your saying that we should just degenerate all software to meet retards needs... yeah it might be good thing for while in terms of profit but eventually you'll kill the whole platform&industry because its so big hassle to buy a) decent product b) people think its platforms fault...

    2. Re:Limiting your market by Uhyve · · Score: 4, Insightful

      Yeah.... No. Developers aren't going to drop half a colour palette because you're too lazy to look into which TVs don't suck.

    3. Re:Limiting your market by tepples · · Score: 1

      Major developers already tend to consolize their games, dropping model detail, texture detail, shader complexity, and complexity of player actions because a lot of gamers are too cheap to buy an up-to-date gaming PC rather than one of the current consoles.

    4. Re:Limiting your market by Anonymous Coward · · Score: 0

      I prefer gaming on the consoles. Money isn't much of an issue with it; I just like having a hassle-free system more than I like maximizing graphics. And even if I didn't, I have no wish to give money to Microsoft (or indirectly supporting them by giving money to other companies in the same ecosystem).

    5. Re:Limiting your market by Penguinisto · · Score: 1

      Not loo long ago, it used to be quite the opposite... Crysis, Unreal Tournament (towards the end of the series), and many more had hardware specs that, while they would technically run on ordinary machines, would almost demand that you go out and buy a fire-breather just to run the stuff. The reason why had less to do with developer ego than with the fact that graphics programming was still mostly in infancy back then, coupled with the fact that GPUs were fairly new tech. Hardware was also evolving pretty damned fast back then - nowadays most improvements are incremental at best.

      (Though to be fair, id Software was historically pretty good about making games that ran fairly well on fairly crap specs.)

      --
      Quo usque tandem abutere, Nimbus, patientia nostra?
    6. Re:Limiting your market by HaZardman27 · · Score: 1, Flamebait

      And even if I didn't, I have no wish to give money to Microsoft (or indirectly supporting them by giving money to other companies in the same ecosystem

      So, since you are a console gamer, which of the wonderful and ethical console manufacturers do you give your money to? Certainly not Sony or Nintendo since they're no better than Microsoft. Who, then?

      --
      Apparently wizard is not a legitimate career path, so I chose programmer instead.
    7. Re:Limiting your market by Anonymous Coward · · Score: 0

      A developer needs to make an application for the hardware people have, not the hardware he wishes people had. Otherwise, he's likely to end up limiting his market to a subset that's not big enough to turn a profit.

      id Software has historically been an exception to that rule. I can honestly say that it was primarily a desire to run John Carmack's code that drove me to make PC, motherboard, video card, and RAM purchases on more than one occasion, and I know I'm not the only one. It's also probably safe at this point to make vague references to clandestine midnight hole-drilling through floors to install private LANs to play Doom on in the workplace that may or may not have been caused by id Software. id Software demonstrated that if a game was truly good enough, it could be targetted to whatever platform they wanted to target, and not only would customers go there, but manufacturers would as well.

    8. Re:Limiting your market by HunterZ · · Score: 1

      I guess that explains RAGE then.

      --
      Arguing about vi versus Emacs is like arguing whether it's better to make fire by rubbing sticks or banging rocks.
    9. Re:Limiting your market by Gr8Apes · · Score: 1

      Sorry, I'd disagree that a developer needs to go to LCD levels (nice overloading of the acronym there:) especially since there's the capability to increase gamma within your OS's display settings, which can make even the darkest of screens seem like they are lit in bright daylight, provided there are contrasting elements in the scene.

      --
      The cesspool just got a check and balance.
    10. Re:Limiting your market by Anonymous Coward · · Score: 1

      You can thank the console makers for holding us back. With everyone wanting to make sure their games can be ported to the most popular consoles, or designing specifically for those consoles and porting to PC, and console makers sticking to 8+ year life-cycles, we have been saddled with increasingly pitiful graphics and associated hardware demands. Nobody with the budget to do so is willing to develop beyond the capacity of a computer that, in a professional environment, would have been retired six years ago.

    11. Re:Limiting your market by Saffaya · · Score: 1

      Once upon a time, there was SEGA and the DreamCast (and Sega Saturn and megadrive/genesis). There was also NEC and the Pc-Engine/turbografx and the PC-FX. SNK and the Neo-Geo also.

      I agree with you all the ethical console manufacturers have died. Just wanted to point out there was a time when we had ethical console makers.

      A compromise can be found by buying the modern console you seek second-hand, so you don't support them directly.

    12. Re:Limiting your market by Grave · · Score: 1

      But you still support them by creating demand. All your games, if new, directly support them--if used, you still support them again with demand.

    13. Re:Limiting your market by HaZardman27 · · Score: 1

      I think it only really creates demand if you don't distinguish between a new copy of Game X with a used copy of Game X. If you make the distinction, then it could be said that you are creating demand for used Game X but not new Game X.

      --
      Apparently wizard is not a legitimate career path, so I chose programmer instead.
    14. Re:Limiting your market by tepples · · Score: 1

      As long as there exist some participants in the market who don't make the distinction between new and used copies, newly created demand for used copies will indirectly increase demand for new copies, especially for games that GameStop and the like still sell new.

  5. His Comment by phantomfive · · Score: 5, Informative
    Here is what John Carmack wrote:

    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.

    --
    "First they came for the slanderers and i said nothing."
    1. Re:His Comment by MobyDisk · · Score: 4, 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.

    2. Re:His Comment by girlintraining · · 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.

      --
      #fuckbeta #iamslashdot #dicemustdie
    3. Re:His Comment by Anonymous Coward · · Score: 2, Funny

      Republicans implemented in emacs lisp.

    4. Re:His Comment by meerling · · Score: 5, Funny

      Especially with the rising symptoms of Dementia and Alzheimers. :)

    5. Re:His Comment by caywen · · Score: 0

      Yes, older, wiser, greedier, selfish, and judgemental.

    6. Re:His Comment by Anonymous Coward · · Score: 1

      Tell her she is confusing wisdom with senility.
      But then again, when asked, I reply "I'm seventy-years young"...

    7. Re:His Comment by jez9999 · · Score: 4, 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.

    8. Re:His Comment by Anonymous Coward · · Score: 0

      So what you're saying is that your Mom is pretty smart? Or just that old people realize that they may not die before they actually have to deal with the long term consequences of their actions.

    9. Re:His Comment by El_Muerte_TDS · · Score: 1

      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.

      That is more or less the same conclusion/train of thought Epic Games' Tim Sweeny had in 2005: http://dl.acm.org/citation.cfm?id=1111037.1111061 (note: slides of the talk can be found on the internet).

    10. Re:His Comment by Rhacman · · Score: 5, Insightful

      As I get older, I gain more experience and hence believe that my opinions carry more weight. Since me and my close knit group of similarly aged friends agree with me it stands to reason that what I have come to believe now is in fact correct and that others who disagree with me are simply immature.

      --
      Account -> Discussions -> Disable Sigs
    11. Re:His Comment by phantomfive · · Score: 3, Interesting

      It actually follows a predictable patter (YMMV no warranty implied etc):

      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.

      --
      "First they came for the slanderers and i said nothing."
    12. Re:His Comment by chispito · · Score: 2

      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.

      --
      The Daddy casts sleep on the Baby. The Baby resists!
    13. Re:His Comment by Anonymous Coward · · Score: 0

      Because that certainly doesn't fit the model of a Democrat...

    14. Re:His Comment by Alomex · · Score: 4, 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.

    15. Re:His Comment by Zero__Kelvin · · Score: 0

      "The third plateau is no longer caring which tool you use, as long as its the best tool for the job."

      The fourth plateau is realizing that Linux is in fact great for everything, and that you were almost right when you were on the second plateau, and then never ever ever again suggesting that Windows is anything but a shit-hole piece of garbage forced upon the ignorant masses by an unscrupulous nitwit named Bill Gates. Don't worry. You'll get there someday.

      --
      Guns don't kill people; Physics kills people! - John Lithgow as Dick Solomon on Third Rock From The Sun
    16. Re:His Comment by Joce640k · · Score: 2

      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.

      --
      No sig today...
    17. Re:His Comment by Creepy · · Score: 1

      He is dead on with the state of STL 10 years ago, as STL wasn't standard in compilers yet and add ons like STLport were buggy on some platforms. I remember supplying plenty of bug fixes at least, and that certainly wasn't 10 years ago.

      As for the article and as an old C programmer that moved to C++, I agree for the most part. I do admit I don't like public val and prefer getVal() setVal() functions, or the opposite of what he said; they may add code, but using them also forces encapsulation, and friend functions have caused debug hell for me more than once (I despise the f**kers, but sometimes they are necessary).

    18. Re:His Comment by aquabat · · Score: 1

      Very subtle, sir. You make a keen observation on the insular nature of our society, but I think your point will go unnoticed by most of the people you are targeting, which is a shame.

      --
      A republic cannot succeed till it contains a certain body of men imbued with the principles of justice and honour.
    19. Re:His Comment by FrangoAssado · · Score: 4, Informative

      That's a fair point, but you have to pay closer attention to what Carmack wrote:

      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.

      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").

    20. Re:His Comment by Anonymous Coward · · Score: 0

      It took me until 26 to become a Republican.

    21. Re:His Comment by Anonymous Coward · · Score: 1

      Smart Lady. When you are young and have nothing to lose, you are more than willing to take from others. When you have spent a lifetime scratching together a life, you actually have something to lose. You actually begin to feel entitled to what you earned and want to keep it and not have some poor beggard taking what you rightfully earned. An Anti-Gun liberal is just someone who's wife/daughter/fiancee hasn't been attacked. Once you are forced to deal with the real world, things start to change from your ideal, let's make a utopian society to, let's try to keep my family safe and fed. Don't worry. You will get there some day. It may be sooner rather than later, and I hope it doesn't take a loved one being attacked to do it.

    22. Re:His Comment by Isaac+Remuant · · Score: 1

      Nope. Democrat stands mainly for Delusion & Denial .

      --
      "Science can amuse and fascinate us all, but it is engineering that changes the world. " - Asimov.
    23. Re:His Comment by Anonymous Coward · · Score: 0

      It's not that they become wiser, is that you can only fool people for so long, except certain people that are so dumb they can be fooled their entire lives.

    24. Re:His Comment by MobyDisk · · Score: 5, Funny

      Mom, I told you nobody mods you up until you register.

    25. Re:His Comment by SourceFrog · · Score: 1

      I for one consistently subject my views to strict rational analysis, using reason.

      --
      My other UID is three digits.
    26. Re:His Comment by SourceFrog · · Score: 2

      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.

      --
      My other UID is three digits.
    27. Re:His Comment by Anonymous Coward · · Score: 0

      Now why the heck you had to bring Apple into this discussion?

    28. Re:His Comment by Anonymous Coward · · Score: 0

      So people just go crazy as they age?

    29. Re:His Comment by Anonymous Coward · · Score: 0

      I love they way this had been modded insightful rather than funny!

    30. Re:His Comment by hermitdev · · Score: 2
      I think the joke/quote actually goes:

      When you're young and you're not a Democrat, you don't have a heart.

      When you're old and you're not a Republican, you don't have a brain.

      Mind you, I think this originated in the Reagan era, when being a Republican meant more about being fiscally conservative than the current social conversative/christian fundamentalists that have hijacked the party.

    31. Re:His Comment by Anonymous Coward · · Score: 0

      Smart Lady. When you are young and have nothing to lose, you are more than willing to take from others. When you have spent a lifetime scratching together a life, you actually have something to lose. You actually begin to feel entitled to what you earned and want to keep it and not have some poor beggard taking what you rightfully earned. An Anti-Gun liberal is just someone who's wife/daughter/fiancee hasn't been attacked. Once you are forced to deal with the real world, things start to change from your ideal, let's make a utopian society to, let's try to keep my family safe and fed. Don't worry. You will get there some day. It may be sooner rather than later, and I hope it doesn't take a loved one being attacked to do it.



      So what you're saying is is that you were just as selfish when you were young. Got it.
    32. Re:His Comment by Anonymous Coward · · Score: 0

      mathematica, you can prototype, visualise and interact with a concept in less code and time, as well as having something that is using state of the art algorithms, and potentially a high performance implementation.

    33. Re:His Comment by Anonymous Coward · · Score: 0

      as you get older, and you forget the details of what happened along the way, you are more likely to attribute more of your place in life to your hard work, dedication, and good old fashioned common sense, and undervalue the input of luck, timing, and being born to the right parents in the right place at the right time.

      and then you look at those who are below you in station, and decide that if they just worked harder, were more dedicated, and had more common sense, they could be in your position too; and that they're not is therefore their own fault, and you don't want to have to subsidise their mistakes. at which point the republican "fuck you, i've got mine" attitude starts to sound like a sane and reasonable option.

      this is not wisdom; this is myopia.

    34. Re:His Comment by epine · · Score: 2

      One might suggest that every good programmer, if they spend enough time improving, eventually moves toward a more functional programming style.

      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 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 in C with C++ influences (a manually coded object as the first function parameter for most functions). Hardly ever used an FP technique. We used to story-board memory flow like an underfunded Hollywood picture. We didn't code in Howard Hughes FP movie-making style a la Hell's Angels where he had a stupidly large number of cameras covering the arial stunt-work, IIRC from The Aviator special features chitchat.

      What movie maker ever turns down twelve camera coverage if you get it for free? Unfortunately, in 640K there are no free camera angles. You've probably borrowed your camera from some studio over the weekend like Ed Wood might have done, hoping they won't miss it over the weekend. One develops habits that work and continue using them as the world changes around you. Some directors acquired a knack of working successfully with one camera, back when film was expensive. It's not such a bad thing.

      Challenge of the day: Efficiently implement Knuth's Dancing Links algorithm in a pure functional idiom.

      One coding technique I like in C/C++ is to reverse the logic of the if predicate so that the less typical condition comes first, often with just a bare statement (no braces) to deal with it, followed by an else clause with braces, that is usually longer, and sometimes quite long.

      The following looks annoying vertical looking to me.

      if (cond1) {// main case
          if (cond2) { // main case
              ; // lots of stuff
          }
          else {
              ; // one statment
          }
      }
      else {
          ; // one statement
      }

      Can you really get into trouble leaving out some braces with the inverted structure as follows?

      if (!cond1) // rare case
          ; // one statment
      else {
          if (!cond2) // rare case
              ; // one statement
          else {
          ; // lots of stuff
          }
      }

      These discussions of style usually just piss me off. Often you get some relatively profient coder blind to his own working methods (to say nothing of the working habits of others) making general observations that are nowhere near as general as they first appear.

    35. Re:His Comment by DamnStupidElf · · Score: 1

      Whoever writes a functional language that understands arrays and pointers will rule the world.

      Intel has a fairly good one, I'd wager. A computer is really just a big iterated function of the current state of the registers, cache, RAM, and I/O devices. If you *really* want low-level hardware access in a functional language that's what it's going to look like in a pure functional language. The CPU is what evaluates the "computer" function and writes its output back to the rest of the hardware in manageable chunks of pure side-effect. Expressing arrays and pointers in a functional language requires modeling the memory-addressing hardware of the CPU.

    36. Re:His Comment by gef7 · · Score: 1

      > Whoever writes a functional language that understands arrays and pointers will rule the world.

      Hey, that's fairly simple in any functional language:

      All you need is to write the function for a pointer machine, whereby you manipulate exactly one structure:
      (InstructionPointer: Integer, RAM[2^n]) # eg. Integer 32bits & n=32 for RAM.
      Then, you just wire the operation SubtractNBranchIfNegative (or equivalent) in the function.
      Input/Output domain of the function is of the same type (the struct, ie. the state machine of this "computer").

      Voila, there you go: functional programming with pointers ;-)

    37. Re:His Comment by Anonymous Coward · · Score: 0

      You're still on the first plateau ;)

    38. Re:His Comment by Rhacman · · Score: 1

      Imagine if you entered a contest to make the best pumpkin pie and for your entry win the prize for best chicken soup. If I point out that I intended to make a pie I risk walking away with a ribbon that says "Participant". I think I'll take my +5 Insightful and go home and eat my... well whatever this is.

      --
      Account -> Discussions -> Disable Sigs
    39. Re:His Comment by shutdown+-p+now · · Score: 1

      Whoever writes a functional language that understands arrays and pointers will rule the world.

      Most functional languages understand arrays just fine - OCaml has rather rich mutable array types.

      "Functional" != "pure". You can have your mutable data structures - and yes, that can include raw pointers - and still write functional style.

    40. Re:His Comment by shutdown+-p+now · · Score: 1

      The difference between then and now is that back then, FP was mainly confined to academic languages with poor tooling and horrible performance profiles. Today, it has found its place into mainstream, "industrial" languages (meaning the kind that millions of lines of codes are written in and maintained over decades), and performance is either fixed, or else we've got machines powerful enough that we don't care about it all that much anymore - lifting locals captured by a closure to heap is now perfectly acceptable, despite the extra heap allocation and indirection that it entails.

      Well, that, and we no longer need to fit code or data into 640K.

    41. Re:His Comment by Rhacman · · Score: 1

      but I think your point will go unnoticed by most of the people you are targeting, which is a shame.

      I thought about it for a moment and upon reflection... I'm comfortable with that ;)

      People who got the joke enjoyed a slight grin.
      People who didn't get the joke felt a sense of comfort in being validated.
      And the people who got the joke enjoyed a slightly wider grin.

      And no, I'm not just targeting politics with that comment. Perhaps we all are drawn to that mentality as we get older. I for one look forward to the day when some young coder calls me out on a genuine flaw in my work. When he or she regains consciousness I hope to shake their hand for showing me that as mature as I think I am, I still have more to learn.

      --
      Account -> Discussions -> Disable Sigs
    42. Re:His Comment by Anonymous Coward · · Score: 0

      Look mommy, another imbecile trying too hard.

    43. Re:His Comment by Anonymous Coward · · Score: 0

      [citation needed]

      (for your mother)

    44. Re:His Comment by Anonymous Coward · · Score: 0

      You will appreciate the wisdom of that remark someday.

    45. Re:His Comment by acheong87 · · Score: 1

      When you have spent a lifetime scratching together a life, you actually have something to lose. [...] Once you are forced to deal with the real world, things start to change from your ideal, let's make a utopian society to, let's try to keep my family safe and fed.

      When you have "spent a lifetime," period, you should be mature enough to understand that taking sides according to your myopic goals focused on your current time and place in life, does not translate to what's optimal for the society as a whole, which, by the way, includes you.

      An Anti-Gun liberal is just someone who's wife/daughter/fiancee hasn't been attacked.

      And you are just someone who wasn't born into an impoverished/unjust family/community/society, and didn't have to work or smile four times as much just to earn the same status, respect, or opportunities that other children were born possessing.

      If you're willing to say that the "young" don't know what theyr'e doing because they haven't yet experienced certain aspects of life, i.e. their future lives, then why stop there? What makes you think that you know what you're doing, given that you haven't experienced certain aspects of life either, e.g. other people's lives?

      Oh, wait, I get it. It's too hard to imagine being born again with a new hand, different family, different culture, and/or different race, and you'll be damned if you ever have to use abstract thought again!

      See: Rawls.

    46. Re:His Comment by Jearil · · Score: 1

      Python is a horrible language and is hard to write for any real sized project.

      Let's say you need to modify a function signature to handle different parameters. Or maybe even rename the function to better reflect it's real purpose. In any compiled language it's dead simple to verify that all users of that function have been updated as well. In python, you what? Grep through the source code and hope you find all of the instances based on the function name? Well what if you passed the function is as a parameter to another function? Well.. you get a runtime error when your code doesn't interpret when running, but by then it's possible that it's already released.

      How about logic bugs that can't easily be found?

      something = function_call(a) ...
      soemthing = function_call(b)

      The soemthing is probably a typo.. Good languages will tell you you never declared a variable called soemthing.. Python will just create it for you. Yay.

      Or even just something like:
      a = "some string"
      a.someFunctionThatDoesn'tExist()

      You have to unit test every possible code path just to know the damn thing compiles. Duct typing is the tool of the devil that doesn't save any time and in fact causes more problems and just wastes developer time. It's impossible to refactor, large projects are a pain in the ass, and import statements do different things depending on how you declare them (Yes, there is a difference between "import module.submodule" and "from module import submodule" and "from module import submodule as some_other_name").

      And whitespace as part of your syntax is just stupid. Oh and Python doesn't have real threading because of it's reliance on a horrible interpreter implementation revolving around the GIL. Oh and you can't have true encapsulation because it's impossible to have private variables in python. And there's not really a thing as a "constant" as it's a pain in the ass to make something immutable.

      If you want something that follows the 3 points you just made, use Scala. It's functional, OOP, can be used as a scripting language.. and it's statically typed so you avoid all the pain in the ass shit you run into with python. Oh and it has threading to boot.

    47. Re:His Comment by phantomfive · · Score: 1

      Let's say you need to modify a function signature to handle different parameters. Or maybe even rename the function to better reflect it's real purpose. In any compiled language it's dead simple to verify that all users of that function have been updated as well. In python, you what? Grep through the source code and hope you find all of the instances based on the function name? Well what if you passed the function is as a parameter to another function? Well.. you get a runtime error when your code doesn't interpret when running, but by then it's possible that it's already released.

      Good point.

      --
      "First they came for the slanderers and i said nothing."
  6. The googles, they do nothing! by Anonymous Coward · · Score: 1

    The only reason to take *screenshots of code* is if you somehow broke copy/paste.

    1. Re:The googles, they do nothing! by Khashishi · · Score: 1

      the author probably didn't want to lose/rewrite the syntax highlighting.

  7. Mostly right, but a few problems. by Anonymous Coward · · 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.

    1. Re:Mostly right, but a few problems. by godrik · · Score: 2

      "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.

    2. Re:Mostly right, but a few problems. by gamanimatron · · Score: 2

      ...there is no good reason to expose bare, public variables on anything but the simplest, most struct-like objects.

      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).

      --
      cogito ergo dubito
    3. Re:Mostly right, but a few problems. by Joce640k · · Score: 1

      "The other thing that rubbed me the wrong way here was public member variables."

      I am puzzled by that as well.

      Me too.

      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.

      I can't see how he values less keypresses over encapsulation/inconsistency.
      a) Is he going to have half the variables in a class as public and the other half with accessor methods?

      b) What's wrong with returning a reference to bar, ie. "foo.bar() += 3;"? That at least allows you to do something if "bar" has any other dependent variables.

      --
      No sig today...
    4. Re:Mostly right, but a few problems. by Khashishi · · Score: 1

      So, somehow, making the state variable private and having a public method to modify the variable is somehow safer? Any code path can still call the public method.

    5. Re:Mostly right, but a few problems. by Zan+Lynx · · Score: 4, 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.

    6. Re:Mostly right, but a few problems. by bzipitidoo · · Score: 2

      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 no comments at all. I also liked the restrained use of blank lines. And, as you say about public variables, it cuts down on the verbosity. I didn't see any mention about the length of variable names, but I have no problem with "Egyptian Hieroglyphics", if you will, that is, dropping vowels from variable names of limited scope. I will also put several short statements on the same line. I see nothing wrong with, for example, assigning data to several member variables on 1 line, like this: "p.x=2; p.y=3; p.z=-4;". particularly when it is often doable as a single simple member copy assignment.

      People who disagree about the desirability of brevity are welcome to use COBOL and XSLT.

      --
      Intellectual Property is a monopolistic, selfish, and defective concept. It is "tyranny over the mind of man"
    7. Re:Mostly right, but a few problems. by Anonymous Coward · · Score: 0

      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.

      You sound like you don't understand encapsulation. What kind of IDE do you use that doesn't simply generate getters and setters for you and hide them down at the bottom of your class (presuming your language doesn't simply do it for you)? That way if you ever need to adjust how a variable gets set (by sanity checking or adding a default value, for example) you can do it once and enforce it system-wide. That's just one of the many benefits of encapsulation.

      I shouldn't have to explain the benefits of either encapsulation or accessor methods here, others have done a better job.

    8. Re:Mostly right, but a few problems. by Anonymous Coward · · Score: 0

      We're all well-aware of the superiority of C#. You don't need to rub it in.

    9. Re:Mostly right, but a few problems. by Darinbob · · Score: 1

      STL however does lead to things that can be extremely difficult to read. Templates in general if not used judiciously can really confuse matters. You can have convenience libraries but they don't have to be as heavily templated or generic as STL. And I can certainly see why "auto" is in the latest standard because you need it to keep your sanity in some of these complex cases. You can do things a different way.

      I am on the fence about public instance variables, they can make things vastly more readable than a plethora of getter functions. Somewhat it's probably due to C++ syntax, because in Smalltalk where you have no public instance variables it's a lot more readable. I don't really buy the argument that other programmers might change things behind your back, as it's not that common a bug and really there's no difference for weird bugs here between a public setter function versus a public instance variable. The real reason for setter/getter functions is in case you want to change the implementation later.

      Look at it this way. If your publicly advertised interface includes an x and a y parameter that can be read and written by everyone, then it is more readable to make these public instance variables instead public getter/setter functions. The drawback is that the implementation becomes tied to these being variables so that it becomes difficult to change. Ie, if you have x and y and later want to have angle and magnitude then it's easier to do if you initially had getter/setter functions. But if you know the implementation won't change in ways that will be difficult to work with, then go ahead and use the public instance variables despite the dogma.

    10. Re:Mostly right, but a few problems. by MarcoAtWork · · Score: 1

      with a setter/getter you can

      - make it thread safe
      - set up defaults
      - set up boundary/sanity checking
      - easily debug any of the sets/gets if you need to

      I don't think saving a few keystrokes is worth giving up all of the above...

      --
      -- the cake is a lie
    11. Re:Mostly right, but a few problems. by hermitdev · · Score: 1

      I can't see how he values less keypresses over encapsulation/inconsistency.

      Especially considering how he insists on prefixing with "get"/"set".

      b) What's wrong with returning a reference to bar, ie. "foo.bar() += 3;"? That at least allows you to do something if "bar" has any other dependent variables.

      The problem with this is that it, too, breaks encapsulation. You've effectively given a pointer (ok, a reference, but we all know they're really the same thing) to your internal memory. And, to your justification, no, it does not allow you to do some if bar has dependents (unless you're not really returning a reference, but an object providing pseudo-reference behavior, a la std::vector<bool>::iterator).

    12. Re:Mostly right, but a few problems. by hermitdev · · Score: 1

      Unexpected modification of public values doesn't get any better when its done through a setter function.

      True, but I can set a breakpoint on a setter function. Not all debuggers/languages support breakpoints on when a variable changes.

    13. Re:Mostly right, but a few problems. by dunkelfalke · · Score: 1

      There is a difference. In a getter/setter pair you can use a read/write lock and sleep soundly, assured that you won't ever forget to unlock if you modify a public variable somewhere.

      --
      "It's such a fine line between stupid and clever" -- David St. Hubbins, Spinal Tap
    14. Re:Mostly right, but a few problems. by Lehk228 · · Score: 1

      the problem with a class allowing other classes to fiddle with instance data is then the "rules" for what states that data can be in are no longer internally enforced by the function. very simple example: class Divider float numerator float denominator float Quotient()

      if somewhere in the program a 0 gets assigned to divider Div.denominator the error does not surface until Quotient is called or until some other place in the code happens to check if Div is in a reasonable state.

      setters and getters should be doing sanity and validation checks and even when they are not, they allow such checks to be added later once they become necessary for long term maintenance (obviously my example is an absurd simplification)

      --
      Snowden and Manning are heroes.
    15. Re:Mostly right, but a few problems. by Zan+Lynx · · Score: 2

      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.

    16. Re:Mostly right, but a few problems. by Darinbob · · Score: 1

      Important state variables of course should not be public. But a lot of simple stuff can be. There's no real distinction beween a setter that does zero checking and a public variable. I suspect that most of those cases where time was wasted tracking down a bug where someone set the wrong value to a variable would also have occurred due to setter functions that didn't do any checking either. That's because the people who are smart enough to be doing checks in a setter function know which variables to not make public already.

      I agree that the setters/getters are nice because of the non-trivial possibility that you will want to change them someday. However this does indeed make the code less readable. It's a tradeoff. Time wasted finding an obscure but where someone sets a variable to a wrong value wastes some development time, however having code that is harder to read also wastes some development time.

      I am on the fence about this as I said. However I do think there's a ton of dogma over this issue, sort of like gotos or multiple returns from a function, people instinctively avoid it because that's what the prof told them or their first mentor on the job.

    17. Re:Mostly right, but a few problems. by Zan+Lynx · · Score: 1

      I do understand encapsulation. I've been writing and maintaining code for nearly 20 years and I've seen how helpful it can be. If it was part of a class that was exposed as a public interface I would totally use getter and setter functions, if I absolutely had to. I find it is generally a lot better to set everything up front in the constructors and mutate the object state in response to verbs. Position->Move() rather than Position->setX().

      You sound like you don't understand when to abandon encapsulation. I imagine you write Java or C# software and your class definitions contain 30 lines of useless code before you even start to write anything.

      What kind of IDE do you use that can't quickly find every use of the x member variable and convert it to a function call?

    18. Re:Mostly right, but a few problems. by Lehk228 · · Score: 1

      if the getter and setter literally only gets and sets, at that point the only reason to keep it around is for consistency with other classes and members, if consistency is not an issue it does not matter at all purely style preference.

      --
      Snowden and Manning are heroes.
    19. Re:Mostly right, but a few problems. by Anonymous Coward · · Score: 0

      C++ supports read only access to public data members via const reference to the container object. If you don't want others to modify your object contents unintentionally, then give them a const reference to your object, with public data members and all. They can still cheat and typecast to non-const ref, but they would have to do so consciously (and they may avoid this by refining the object API instead). If you truly need to hide implementation details (data members) and provide a stable ABI -- use a Pimpl.

      const references, constructors, destructors, RAII, templates -- that is why I love C++.

    20. Re:Mostly right, but a few problems. by dunkelfalke · · Score: 1

      If you need to update a whole batch of variables or a complete structure at once, you write a single setter for it. Besides, it is far simpler to look for deadlocks at one single place than all over 20 source files

      --
      "It's such a fine line between stupid and clever" -- David St. Hubbins, Spinal Tap
    21. Re:Mostly right, but a few problems. by Anonymous Coward · · Score: 0

      There's zero difference between a public getter/setter pair and a public variable.

      That's not entirely true. I am not sure if this applies to C++, but in C#, using a property you can set a breakpoint in it's getter or setter so that you get notified anytime it's updated. With a naked variable, it can be updated at any time by anything without giving you a chance to break

    22. Re:Mostly right, but a few problems. by Anonymous Coward · · Score: 0

      I'll tell you another reason to use public member variables: OOP doesn't have such a thing as a "public readable" variable

      I think what you wanted to say is: C++ doesn't have such a thing as a "public readable" variable.

      With a strict interpretation of OOP, variables are not public ever, so you cannot use public member variables anyway.
      Otherwise, supporting public-readable variables would not be less, but more OOP than just supporting public-writeable variables.

    23. Re:Mostly right, but a few problems. by shutdown+-p+now · · Score: 1

      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.

      OOP is a high-level concept - it doesn't even have such a thing as "public", much less such intricate details. It's all about what languages make of it.

      And, yes, there are mainstream OOP languages that can do what you want. E.g. in C#, you do that with an auto property and explicitly specify a different visibility for the setter:

      public int Foo { get; private set; }

      (Pretty much any combo is supported - you could have the setter protected or internal, or you could have the property protected while the setter is private etc; and you could also reverse it, so that non-member functions can write the property but not read it, though it doesn't really make any sense for API design)

    24. Re:Mostly right, but a few problems. by OdinOdin_ · · Score: 1

      The problem is we don't have access to everybody elses code! Even more of a problem in C++ these direct access to public members will not route via a symbol. This means now I can not change it in future without breaking all the consumers.

  8. Re:Else ifs - yuck by ledow · · Score: 2

    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.

  9. This is a must ... by gstoddart · · Score: 1

    According to id's Doom 3 coding standard, they use real tabs that are 4 spaces. Having a consistent tab setting for all programmers allows them horizontally align their class definitions

    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 leave the code in a usable state because his commits were leaving the whitespace as complete useless crap to everything else.

    I don't care what editor you use, but it needs to leave the files in a usable state for everybody else. Having special formatting to work with your editor just pisses everybody else off.

    --
    Lost at C:>. Found at C.
    1. Re:This is a must ... by Hatta · · Score: 2

      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.

      --
      Give me Classic Slashdot or give me death!
    2. Re:This is a must ... by jez9999 · · Score: 3, 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.

    3. Re:This is a must ... by sourcerror · · Score: 3

      Except that will throw off diff.

    4. Re:This is a must ... by Dr_Barnowl · · Score: 2

      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 rude, the hallmark of a prima donna programmer who's never worked with others.

    5. Re:This is a must ... by Hatta · · Score: 1

      This royally fucks up your version control history.

      That sounds like a problem with version control software.

      --
      Give me Classic Slashdot or give me death!
    6. Re:This is a must ... by Ash+Vince · · Score: 1

      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.

      Someone else has told you why this is stupid idea but only in 7 words, so I wanted to elaborate: Your approach means that when you check the code back into your chosen versioning system every single line will come back as changed rather than just the lines you changed. That means you have to spend more time figuring out what was actually being changed.

      You might as well change every line to have a different carriage return format while your in there just for kicks. Ok, it is trivial in both cases to work around, but why cause your co-workers any extra hassle what so ever. Instead try and make things as easy for them as you possibly can.

      --
      I dont read /. to RTFA, I read /. to offend people in ignorance.
    7. Re:This is a must ... by Dr_Barnowl · · Score: 1

      Version control software is written to be generic - in the main, it doesn't try to understand the files you feed into it. It treats everything as a text file (unless it's obviously not). The only concessions to this are the features for line end munging written into some systems (which probably make most sense on mixed-OS projects), and the provision of hooks that can occur as the result of some events (before you commit, after you commit, etc).

      The upside to this is that you get VCS software that works for the majority of programmers resources without messing with them. Something that stripped indents and then tried to infer what they should be from code structure would totally destroy Python code, where the indent IS the code structure.

      The downside, as you note, is that it doesn't hold your hand or enforce conformity.

      Using hooks for this is a problem because there's always one ass who doesn't set them up. What's that - use the VCS itself to distribute hooks? Massive security hole - commit an evil script and watch the chaos.

      Using IDE settings for this is a problem because while some settings will matter - code indenting, etc - other settings will not, and will antagonise needlessly - fonts, colours, etc. Even if you settle on the default settings shipped with your standard IDE (which I think is in the main very sensible because it's at most likely to be the settings that are configured on any given machine), some of them behave differently by default on different platforms (Eclipse, for example, uses CRLF on Windows and LF on Linux/Mac, and uses the default Java code page - CP1252 on Western Windows and UTF-8 on most Linux and Mac).

      Some editors understand hints in the code file (vim). Some editors guess what the indenting should be from what's already in the file, but know nothing about the other points of code formatting like those mentioned in the document linked to the article.

      Some build systems can configure your IDE for you (Maven). But you can't always force people to all use the same IDE. Or to do anything.

      In other words, it's a big thorny problem with no universal solution. And the kind of guys who write version control systems are in the main, the kind of guys who expect other guys to grow up, be a professional, and review their diffs before they commit them to make sure they aren't ruining everyone else's day. The audience of people who use VCS software is currently mostly limited to people you can at least explain this concept to, so it's less hassle on a case-by-case basis to chew them out and get them to behave nicely, than it is to be that first guy who implements a VCS that understands the structural nuances of the languages involved.

      There have been some attempts to produce programming languages / files that don't have any whitespace, and only consist of structured files, and that get rendered in the style of your choosing by the IDE, but they haven't taken off for a couple of reasons..

      i) The VCS software doesn't understand the files
      ii) You have to have the particular IDE for them, which limits the options of programmers for editing the files, which they hate

      VB6 suffered from this to a degree - forms had resource files defining the properties of the form which seldom merged right - some regions were encoded binary, etc. They fixed this in .NET - the IDE generates code that defines the form. You can edit the code, or the form using the IDE, and it round-trips properly. And because it's code, it merges using standard VCS tools.

    8. Re:This is a must ... by Ksevio · · Score: 1

      That's why the good version controls have an "ignore whitespace" option when comparing versions.

    9. Re:This is a must ... by Darinbob · · Score: 1

      I hate tabs. HATE them. Use spaces. Just about any programming editor is capable of indenting by using spaces. The problems with tabs is that you have to set up the editor to know exactly what a tab means, and everyone has a different idea! If you work on different projects with different tab stop styles then you're changing your editor settings all the time. Ditch the tabs and just use spaces and it's so vastly simpler. And believe it or not kiddies, tab stops historically were almost universally eight spaces, NOT four.

      In emacs you just do "untabify".

    10. Re:This is a must ... by hermitdev · · Score: 2

      I wholeheartedly agree with this sentiment. A lot of developers have personal preferences on their indentation. I worked on a project where distinct devs used 2, 3, 4 and 8 spaces as a single indent. My argument was it was all visual. If we stuck with hard tabs, each could configured their editor of choice to display however they liked, without affecting any other developer. I used to use tabs for alignment, as well, but have since changed to using spaces for that.

    11. Re:This is a must ... by Anonymous Coward · · Score: 0

      he didn't say anything about committing the rearrangements

    12. Re:This is a must ... by Hatta · · Score: 1

      Thanks, I enjoyed reading that and understand better now.

      --
      Give me Classic Slashdot or give me death!
    13. Re:This is a must ... by Anonymous Coward · · Score: 0

      man diff

      diff -b -B ignore white spaces and new lines there's even a flag for tabs

    14. Re:This is a must ... by Marxdot · · Score: 1

      Well and good if you don't use a proportional font.

    15. Re:This is a must ... by Darinbob · · Score: 1

      Hmm, do people actually program with proportional fonts?

    16. Re:This is a must ... by Anonymous Coward · · Score: 0

      Except if you don't fix the tab size then that beautifully formatted method list cited in the article will fall apart the moment someone chooses a different tab size. The only way it will look the exact same for everyone is if you only use spaces.

    17. Re:This is a must ... by jones_supa · · Score: 1

      If you work on different projects with different tab stop styles then you're changing your editor settings all the time.

      If the code is properly written, it does not matter in which tab settings you view it in.

    18. Re:This is a must ... by Darinbob · · Score: 1

      It does because not everyone uses tabs. So you get a mix of spaces on some lines and tabs on others and a resulting mess.
      Or also very common, someone likes to use 3 or 4 character tabstops, and you end up viewing it with standard 8 character tab stops and the lines wrap around in the editor. And even if they don't wrap around, 8 character indentation is not the easiest to read.

  10. Re:Else ifs - yuck by Dan+East · · Score: 2

    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 to that extent.

    --
    Better known as 318230.
  11. Re:Else ifs - yuck by gbjbaanb · · 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.

  12. Re:Else ifs - yuck by Anonymous Coward · · 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.

  13. Re:Else ifs - yuck by Anonymous Coward · · Score: 0

    You don't even know what you don't know

  14. Re:Else ifs - yuck by Deltaspectre · · Score: 2

    Looking at the article, I see nothing that could have been a switch statement. The only else-ifs I see are in the Spacing section, and they need to check if a value is less than or greater than, something that can't be done with a switch.

    --
    My UID is prime... is yours?
  15. Comment-free programming by swillden · · 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.

    --
    Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
    1. Re:Comment-free programming by Anonymous Coward · · Score: 2

      I personally like comments and believe that their usage should be reduced when convenient, it should not be avoided whenever possible. In the article he brings up the following snippet as an example:

      int idSurface::Split( const idPlane &plane, const float epsilon, idSurface **front,
              idSurface **back, int *frontOnPlaneEdges = NULL, int *backOnPlaneEdges = NULL) const;

      And says the following comment is completely unnecessary:
      // splits the surface into a front and back surface, the surface itself stays unchange

      The amount of time required to write, read and understand the comment is far less than the amount of time needed to read the code, parse each section and understand it, especially after not looking at it for 3 months. Even though the function might seem obvious to a veteran C++ programmer, the comment defiantly nice for those less adept.

    2. Re:Comment-free programming by Anonymous Coward · · Score: 1

      I agree that comments do not always help and can obscure the code. But there are many cases when it would be helpful to know why a particular choice was made. Comments help record that history. Also function names, no matter how descriptive, are often ambiguous. Sometimes a comment can help clear up the possible confusion. Coding standards should include what comments to not include. If the comments simply repeat what the source if obviously doing, then those comments clearly can be eliminated. But it's not always obvious why a certain algorithm is used over others, or why a certain magic number is used (some "magic" numbers are necessary so they cannot all be eliminated. It's nice to know how a particular number was chosen).

    3. Re:Comment-free programming by Anonymous Coward · · Score: 0

      You still might want to comment the code that isn't there. This is code that when looked at naively will be expected by someone in the future. But if you decide you don't need it, comments can explain that reasoning whereas there is no code there to explain it.

      Just one example of where you need comments.

    4. Re:Comment-free programming by Rockoon · · Score: 2

      This is spot on but let me give my observation of when and why this is true.

      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 the programmer informed about the nature of the data being juggled by those operations.

      In this way, a local understanding of the program doesnt require a global inspection. None of this is being done to help the programmer on the day he writes the code. It is always done to help a programmer that does not have a fresh internalized global model of the program either because its been months or years since he write it, or because someone else wrote it.

      --
      "His name was James Damore."
    5. Re:Comment-free programming by Anonymous Coward · · Score: 0

      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.

      This is a laudable practice.

      I don't agree with all of your comments, but I agree with your general attitude.

      To me, comments are best if they are guidelines that help the reader understand the code. For example, if you are writing a line drawing function and it implements the Bresenham algorithm, the name of the function should just be "line_draw()" or similar (if you change the algorithm you shouldn't need to do a mass search-and-replace in your code!) so I don't agree that the name of the function should explain everything the reader needs to know. There should be a comment that says "line_draw(): draw a line using Bresenham algorithm". Don't make the reader guess! And I even include a link to Wikipedia for algorithm comments. If someone is trying to understand my code, help can be just a click away.

      As another example, I once wrote code to keep track of how reliable a network connection was. I used an exponential moving average, and put a link to the Wikipedia page; but I decided to add a bonus when the connection was reliable at least ten times in a row, and subtract a penalty when the connection was unreliable at least ten times in a row. (With a pure EMA, you will never quite reach 100% ever again after any problem, and you will never quite reach 0% no matter how many problems. I wanted the reliability to go straight to 0% if the connection was completely broken.) Anyway, a few terse comments explained why the bonus and penalty code was there and how it worked.

      I agree that comments like

              x += 3; // add 3 to x

      are stupid. Everyone can spot an example that egregious, but I have seen plenty of comments that are really not much better. Change the literal 3 to some sort of named constant that is self-documenting, and just delete the comment.

      (And please, in C or C++, use a static const value or an enum rather than a #define. When I'm debugging, the debugger can show me the value for a constant, but a #define makes me dig through the code to figure out the value.)

      In summary: comments are valuable when they explain why the code is a certain way, but should almost never explain how the code works. Let the code speak for itself on the how.

    6. Re:Comment-free programming by swillden · · Score: 1

      Where there is no other way to convey all relevant information, comments are indeed appropriate. I find that there are far fewer such cases than I once did, though, with appropriate effort to make the code itself express the information. And often that extra information shouldn't be only in the code, it should also be in the generated documentation, which further reduces the number of needed non-document comments.

      --
      Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
    7. Re:Comment-free programming by swillden · · Score: 1

      That would be a sub-case of "bits of code that do something which apparently could be done differently but for some other reason must not".

      --
      Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
    8. Re:Comment-free programming by swillden · · Score: 1

      The amount of time required to write, read and understand the comment is far less than the amount of time needed to read the code, parse each section and understand it, especially after not looking at it for 3 months. Even though the function might seem obvious to a veteran C++ programmer, the comment defiantly nice for those less adept.

      While this may be true, it ignores another non-trivial cost to comments: They must be maintained -- and very often are not.

      Almost inevitably, if the code lives long enough the comment will become wrong, and when that happens the comment has negative value, in fact it often has great negative value, as it may mislead engineers into making incorrect assumptions and cause bugs which would have been avoided had they read the code.

      On balance "because it's easier for non-adept programmers to read" is the worst reason for writing comments. It's far better to assume that the readers of the code know how to read the code, or will learn how by doing it. Giving them comments as a crutch not only increases the likelihood that they misunderstand what the code really does (as opposed to what the comment says it does), but also obscures their need to learn how to read code quickly and accurately, which is an absolutely crucial skill. I use the word "obscures" rather than "obviates", or similar, because it's the right word. Being able to read the comment doesn't make it unnecessary for them to learn to read the code, it just hides the fact that they need to learn to read the code.

      I should mention that documentation comments (as well as other forms of documentation) suffer even more from creeping inaccuracy than more localized comments. But assuming the documentation is necessary there's no way to avoid that short of moving to a full literate programming style.

      --
      Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
    9. Re:Comment-free programming by swillden · · Score: 1

      Both of your examples are special cases of the "this code implements a sophisticated algorithm which needs to be explained" situation, in which I agree comments are appropriate. Actually, though, in both cases the details you mention should really be in the doxygen/Javadoc/whatever documentation-generating comments.

      --
      Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
    10. Re:Comment-free programming by Darinbob · · Score: 1

      Do you deal with devices? Where register A must be set before register B? How do you write code that documents this in such a way that a later programmer doesn't come along and say "that's inefficient, let me move the order around"?

    11. Re:Comment-free programming by darkwing_bmf · · Score: 1

      The best use of comments I've seen is as a "user's guide" to functions and procedures that are meant to be used by others, essentially defining the API and relevant notes.

    12. Re:Comment-free programming by Darinbob · · Score: 1

      I've definitely been bit by lack of comments. I knew exactly what the code was doing, I just didn't understand why it was doing it. Ie, I kept maintaining some minor code snippet and making sure it kept working after my changes to the larger code. Only later discovering that this featurette was only ever needed as a workaround for one customer for an ancient release and it would have been better to remove it.

      The "why" of the code is hard to self document. If you don't know the why of the code you often end up leaving it untouched like some cargo cult programmer. Don't know why there's a zero length packet being sent between every data packet so you're unsure if it's correct code or not. Over the years more and more programmers leave it alone without knowing what it actually does.

      Sometimes things are just wrong too. I went a year without knowing what a "saclingFactor was", assuming it was some domain specific name. Turns out it was a typo and no one wanted to change the header file because builds took so long so they just kept using it.

      And sometimes when you do see code that does one thing and a comment that says something else, then you know you've got a potential problem that needs fixing.

    13. Re:Comment-free programming by swillden · · Score: 1

      The best use of comments I've seen is as a "user's guide" to functions and procedures that are meant to be used by others, essentially defining the API and relevant notes.

      Yeah, that's an excellent use of comments. Even better if you format them so you can automatically extract them and create a nicely-formatted user guide (e.g. Javadoc, Doxygen, etc.).

      --
      Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
    14. Re:Comment-free programming by swillden · · Score: 1

      Do you deal with devices? Where register A must be set before register B? How do you write code that documents this in such a way that a later programmer doesn't come along and say "that's inefficient, let me move the order around"?

      It's been a long time since I did much bare metal programming. Commenting code like you describe would be an example of what I called "bits of code that do something which apparently could be done differently but for some other reason must not".

      --
      Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
    15. Re:Comment-free programming by Maow · · Score: 1

      I agree that comments do not always help and can obscure the code. But there are many cases when it would be helpful to know why a particular choice was made. Comments help record that history. Also function names, no matter how descriptive, are often ambiguous. Sometimes a comment can help clear up the possible confusion. Coding standards should include what comments to not include. If the comments simply repeat what the source if obviously doing, then those comments clearly can be eliminated. But it's not always obvious why a certain algorithm is used over others, or why a certain magic number is used (some "magic" numbers are necessary so they cannot all be eliminated. It's nice to know how a particular number was chosen).

      This is the most important reason for a comment's existence, IMHO.

      Nothing more frustrating than a comment saying, $x++ // "add 1 to $x" with no idea why we're incrementing $x; leaving me to play computer in my head / on paper / in a debugger to try to figure it out for myself.

    16. Re:Comment-free programming by rho · · Score: 1

      Auto-documentation is good stuff nowadays. Everything changes so much, and so quickly, that enforced documentation standards lead to better understanding of the underlying API or intent.

      (As an example, why is PHP so popular? It's not because it's beautiful, or elegant. It is, however, very accessible, largely due to good documentation.)

      Good comments--that are not prescriptive for whatever autodoc tool you use--are invaluable, but bad or marginal ones do more harm than good, especially in interpreted languages. You can condense 4 lines of comments into a 22-character, well-constructed function call/local variable and accomplish the same goal.

      --
      Potato chips are a by-yourself food.
    17. Re:Comment-free programming by swillden · · Score: 1

      Good comments--that are not prescriptive for whatever autodoc tool you use--are invaluable, but bad or marginal ones do more harm than good, especially in interpreted languages.

      I'm even skeptical of good comments because of their tendency to become misleading over time. The ultimate authority on the function of the code is the code itself, so if there's any way the code can be made readable enough to eliminate the need for the comment, that's the better choice, and that's true even if reading the code is slightly harder than reading the comment. Now, if the comment is an order of magnitude faster to grok than the code can be, even in it's clearest and cleanest form and assuming an experienced programmer who is good at reading code, then I think there's an argument for the comment.

      And, of course, if there's information which simply cannot be expressed in the code, comments are essential.

      --
      Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
    18. Re:Comment-free programming by Ambient+Sheep · · Score: 2

      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 worked, the project leaders have just not been organised enough to do any of that. It would get lost, separated from the source code, or outdated in pretty short order. Unless it's a massive specification document, generally best to put such info in a big comment block near the top of the function, or module, I've found.

      In general though, I agree with you. With well chosen names, code structure, and data structure, the actual code should largely explain itself.

  16. Work of art. by equex · · Score: 1

    Indeed the code is beautiful and well organized. I think it took me 10 minutes to locate and disable the copy protection, after spending 30 minutes just marveling at the organisation and targeting out code i'd like to steal later. (mostly physics and maths!) Another 5 minutes cleaning up something i don't remember to have it compile. Source download -:> Ready executable ~ 45 minutes. (compiled on an x6).

    --
    Can I light a sig ?
    1. Re:Work of art. by Anonymous Coward · · Score: 1

      An x6? Boy are you in luck. I have an x80 module I'm willing to sell you that will bring you in line with standards!

    2. Re:Work of art. by Anonymous Coward · · Score: 0

      You do realize the copy-protect was removed in the last patch, right?

  17. Most of His Admiration Is Not Technical by Greyfox · · Score: 5, Insightful
    Most of his admiration appears to be issues of code formatting and lack of comments, not the technical design of the code. He started to lose me even before his rants on the ugliness of STL and boost libraries. Do the objects play well together? Is it easy to assemble them to accomplish tasks in sensible ways and with as little set-up as possible on the part of the user of the library? These were not questions I saw answered.

    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.

    --

    I'm trying to teach myself to set people on fire with my mind... Is it hot in here?

    1. Re:Most of His Admiration Is Not Technical by phantomfive · · Score: 3, 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.

      --
      "First they came for the slanderers and i said nothing."
    2. Re:Most of His Admiration Is Not Technical by frinsore · · Score: 0

      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.

      And I would rather have no comments than comments that are incorrect or misleading which cause me to become confused.

    3. Re:Most of His Admiration Is Not Technical by loshwomp · · Score: 1

      Indeed. I would rather have too many comments, to the point that some are not needed, than too few, and remain confused.

      And I would rather have no comments than comments that are incorrect or misleading which cause me to become confused.

      ...and that's a false dichotomy. No one is defending a need for incorrect or misleading comments.

    4. Re:Most of His Admiration Is Not Technical by Greyfox · · Score: 1
      Indeed. And a lot of code maintenance is determining what was going through the heads of the people who came before you. Most of the time they left, either immediately before you arrived or long before you arrived if the code base has already been through several hands.

      A commonly cited object to comments is that you can change the code but not the comments, and then the comments become confusing. In fact that provides me several clues about previous maintainers and possibly even the original design of the code itself. At this point in the game I'm more of an archaeological detective and less like a programmer. Knowing something of the abilities of the previous programmer also lets me know how long I should respect his designs and learn my way around the code base before starting to change things.

      --

      I'm trying to teach myself to set people on fire with my mind... Is it hot in here?

    5. Re:Most of His Admiration Is Not Technical by Dixie_Flatline · · Score: 1

      If the people that you're working with are bad enough that they're leaving incorrect comments in, the code probably isn't much good either.

      It's a false equivalence, in any case. Good comments make code easier to read. As far as I know, nobody was brought up with C as their first language, and so are more expressive in a natural spoken language.

      Bad comments do clutter things up, but nobody is saying you should comment poorly.

    6. Re:Most of His Admiration Is Not Technical by Anonymous Coward · · Score: 0

      No one is defending a need for incorrect or misleading comments.

      No, but university programming classes are making students put lots and lots of comments into their code. And code does get changed without the comments being updated, especially when the comments are in a big block at the top of a long function. (Few programmers are so lazy that they would edit a line of code with a comment at the end of the line, and not edit that comment. But someone might fix a bug without even realizing that he/she just invalidated a comment in the wall of text at the top of the function!)

      And if you read a comment and believe it, it might convince you that the code you are looking at couldn't possibly be the source of the bug you are trying to find. (Example: a comment saying "this function doesn't modify the data structure" but somewhere in the function there is code that does modify the data structure.) An untrue comment can send you down the wrong road and cost you a lot of time. It only has to happen once to make you leery of bad comments.

      So no, nobody is defending bad comments. But the people who want lots of comments have to realize that sometimes, comments do get turned into bad comments, and the more comments you have the more the chance this will happen.

      IMHO the ideal is to write clear code that speaks for itself. That's not always possible, so I'm not in the "never write any comments" camp. But if you can write your code so that it speaks for itself, do it and don't bother to comment it.

    7. Re:Most of His Admiration Is Not Technical by hermitdev · · Score: 1

      A commonly cited object to comments is that you can change the code but not the comments, and then the comments become confusing. In fact that provides me several clues about previous maintainers and possibly even the original design of the code itself.

      I don't know that I've ever seen anyone state that you can't change the comments, but rather the objection is that people don't change the comments to properly reflect changes they've made during maintenance.

      I'd posit that the vast majority of misleading comments don't come from the initial development, but rather during maintenance cycles.

    8. Re:Most of His Admiration Is Not Technical by Anonymous Coward · · Score: 0

      This.

      I was going to write just this. This "beautiful code" could be the output of a pretty-printer and frankly I see very little value in this.

    9. Re:Most of His Admiration Is Not Technical by hibiki_r · · Score: 1

      In places where code is expected to have to be maintained years later, there are ways to get what you want and minimize comments, like Specification by Example and unit tests. If your design is so complicated that the automated specifications and the unit tests do not cover, then sure, comment away, but that should be a very rare event.

    10. Re:Most of His Admiration Is Not Technical by phantomfive · · Score: 1

      And I would rather have no comments than comments that are incorrect or misleading which cause me to become confused.

      I wouldn't. You become confused because you misunderstand the purpose of comments, you expect them to be accurate. A comment represents what someone thought about the code at a certain point in time, nothing less. It could have changed, it could have been wrong at the time.

      If you take that attitude, you will realize that even wrong comments can be helpful.

      --
      "First they came for the slanderers and i said nothing."
    11. Re:Most of His Admiration Is Not Technical by Anonymous Coward · · Score: 0

      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.

      And I would rather have no comments than comments that are incorrect or misleading which cause me to become confused.

      Ah, but is it more likely that the programmer will make an error in the comment, or an error in the code?

      Given

      int idSurface::Split( idPlane &plane, const float epsilon, idSurface **front,
                      idSurface **back, int *frontOnPlaneEdges = NULL, int *backOnPlaneEdges = NULL) const;

      // splits the surface into a front and back surface, the surface itself stays unchanged

      is it more likely that the programmer screwed up on the assertion that the surface stays unchanged or that the programmer dropped a const somewhere?

  18. Re:Else ifs - yuck by Anonymous Coward · · Score: 0

    Switch() may be faster (depending on what your compiler does), but is only "far" faster when you have "a lot" case statements that can directly map to the else if conditions.

    Refer to this:
    http://stackoverflow.com/questions/767821/is-else-if-faster-than-switch-case

  19. Re:Else ifs - yuck by phantomfive · · Score: 4, 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.

    --
    "First they came for the slanderers and i said nothing."
  20. Not really exicted... by Jintsui · · Score: 1

    Lets face it, its 8yo code.....

    1. Re:Not really exicted... by Joehonkie · · Score: 1

      Yeah, I mean with all these other awesome high end game engines that have been open sourced in the meantime, who even cares, right?

    2. Re:Not really exicted... by Anonymous Coward · · Score: 0

      Let me guess, an iphone user?

    3. Re:Not really exicted... by Darinbob · · Score: 1

      Yes, because in the intervening eight years there have been major quantum leaps in code quality and beauty. Most game programmers weren't even born eight years ago.

  21. C++ for the C++ness of it by caywen · · Score: 2

    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.

  22. Const for pass by value is poinltess by Anonymous Coward · · Score: 0

    It is pointless to make f(const float parm) const because it cannot change whether it is const or not. C++ passes by value. If you really want to be purposeful say f(const float& parm). This is a basic review item. Read Lakos. The author doesn't know what he is doing.

    1. Re:Const for pass by value is poinltess by Anonymous Coward · · Score: 0

      It is pointless to make f(const float parm) const because it cannot change whether it is const or not. C++ passes by value. If you really want to be purposeful say f(const float& parm). This is a basic review item. Read Lakos. The author doesn't know what he is doing.

      It's pretty clear that you don't know what you're doing. f(float parm) means that I can assign to "parm" in the function body, even if that assignment is not visible outside the function. f(const float parm) means that I can't assign anything to "parm" in the function body, because the compiler will flag that as an error. If you don't know why the latter is useful, you don't know what you're doing.

  23. Re:Else ifs - yuck by timeOday · · Score: 2
    "Far" faster? Well, maybe percentage-wise. But I bet it would be 0.0001% of program execution for one and 0.00013% for the other. Worrying about the relative speed of alternate constructs and using them everywhere is a backwards approach; instead, find out what's taking most of the time in your code using a profiler, fix it, rinse and repeat.

    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 subclassing and virtual functions.

  24. Re:Else ifs - yuck by Anonymous Coward · · Score: 0

    Oh, another moron.

    Case statements can be optimized using jump tables.

  25. Reply with by Anonymous Coward · · Score: 3, Funny

    "Things seem wiser when you become older and senile"

  26. Beauty is in the eye of the editor by Anonymous Coward · · Score: 0

    I read this article yesterday when it was on Kotaku. I have some issues with some of the statements, several of which (such as comments and {} formatting) really depend on the editor being used.

    I think the author believes that the Doom 3 code is beautiful because it matches his own coding style preference. Truly beautiful code is beautiful not because of style, but because the code is extensible, robust, and maintainable. Many of the arguments in the article touch on several of those points, but don't really tie in strong enough to definitively prove the code to be beautiful. For me, the most important of those three is the last mentioned, maintainable. A programmer is happy when the code they must maintain (perhaps written originally by another person or team) is easy and straight forward to maintain. Robustness and extensibility tie into maintainability. I say code is beautiful when I can spend minimal time fixing errors and maximizing the number of new features in that code.

  27. Re:Else ifs - yuck by meerling · · Score: 2

    Well of course. If you knew what you didn't know, you'd know it instead of not knowing it, you know?

  28. Re:Yeah... and... by meerling · · Score: 1

    Don't forget the grays and blood reds of the standard ID color palette.

  29. Re:Else ifs - yuck by Anonymous Coward · · Score: 0

    Not neccessarily. If the processor architecture/assembly language supports jumps/branches relative to the program counter, and the case statements are sequential values, you can setup a jump table. That way, you jump by on offset based on your case value, which leads directly to a second jump statement to the relevant batch of code. This makes it so you don't have to check every condition until you get to the one you need.

    It's been awhile since I've played with it, but the trick works in x86, and a good compiler will use it. However, I was never able to find an equivalent trick for Power/PowerPC.

  30. lost me by j00r0m4nc3r · · Score: 3, Interesting

    after the first three conclusions, and i stopped reading so i can't speak for the rest. should be: 1.) const as appropriate, not "const everything possible". const can fuck you hard in OOP if you use it wrong, 2.) you can never have too many comments, and 3.) tight vertical spacing is archaic and stupid, unless absolutely necessary for some display reason

    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...

    1. Re:lost me by Anonymous Coward · · Score: 1

      I mostly agree, but yes, you CAN have to many comments. I once was on a project were the existing code had literally paragraphs of comments per line of code. I am not exaggerate. It was extremely hard to read that code.

    2. Re:lost me by StormReaver · · Score: 3, 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.

    3. Re:lost me by lorinc · · Score: 2

      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 styles. From my experience, it seems these kind of coding gurus tend to write code that bugs less often, and manage to maintain code of other gurus far better than non-gurus do with non-gurus code. It seems they are in a sort of tight cluster where they do communicate very well with themselves, while the rest of the programmers have high difficulties to communicate, whatever the number of redundant comments they write.

    4. Re:lost me by HonIsCool · · Score: 1

      Please explain how "const can fuck you hard in OOP".

      --
      "Give me six lines of C++ code written by the most competent programmer, and I will find enough in there to hang him."
    5. Re:lost me by dkf · · Score: 1

      K&R is perhaps the single ugliest coding style I have ever seen or used.

      You wait till you encounter "traditional FORTRAN" style, which can be characterized as (approximately) "Indentation? What's that?" It is a number of years since I worked with someone who wrote that way by choice, but it is still a clear reminder that most people's indentation isn't that bad. Yes, if you were coding in FORTRAN77 then you might write stuff that way, but this was in C...

      Personally? As long as the indentation step is at least 3 and is consistent through the codebase, I'm not too fussed. And 8 is usually excessive.

      --
      "Little does he know, but there is no 'I' in 'Idiot'!"
    6. Re:lost me by mandolin · · Score: 1

      K&R is perhaps the single ugliest coding style I have ever seen or used.

      Let me introduce you to the GNU coding standards. Please pay particular attention to the crazy way they indent the braces in the function body.

    7. Re:lost me by Marxdot · · Score: 1

      OOP

      you can never have too many comments

      tight vertical spacing is archaic and stupid

      Speaking of religion...

    8. Re:lost me by ShakaUVM · · Score: 1

      >3.) tight vertical spacing is archaic and stupid, unless absolutely necessary for some display reason

      Mentally, we can deal with code that is chunked together on the screen. This is why I wrote my code folding patch for Vim - you could search for a keyword, and fold away all the code that didn't match it (and include lines of context around each hit).

      So if you were refactoring, and wanted to look at each instance of your initfooblah member function, by just searching for initfooblah, all the relevant code would be on the screen, and everything else would get folded away.

      Even doing something as simple as hitting n to move to the next hit causes a mental wipe, which can cause you to refactor the next line slightly differently and introduce a bug, because it's not all on the screen together.

      As a Master's Student in CS, I thought a *lot* about the mental process of coding, and avoiding these mental wipes.

    9. Re:lost me by Anonymous Coward · · Score: 0

      You talk about "religion" yet here you are saying vertical spacing is stupid. It is a style preference, each individual to his/her own. If you like too much "religion" then to each their own on spacing, so you are contradicting yourself here. Sounds like you don't practice what you preach. Where did you say you work again?

    10. Re:lost me by j00r0m4nc3r · · Score: 1

      Example #1. If you over-const, people will eventually cast it away rather than completely refactoring a class hierarchy.

    11. Re:lost me by j00r0m4nc3r · · Score: 1

      I didn't say "any religion", I said "too much religion". There is a difference, but I don't expect you to get it...

  31. Re:Else ifs - yuck by Anonymous Coward · · 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.

  32. Re:Else ifs - yuck by Anonymous Coward · · Score: 0

    Under equivalent circumstances, the same could be done with an if/else-if chain. And jump tables aren't always faster.

  33. Re:Else ifs - yuck by hey · · Score: 1

    Probably for a small number of tests else-if is faster (and easier). But when the number of tests is larger I would think switch() would be faster.
    (switches us a jump table.) I agree timing is the only way to tell. If you are checking all possible values of a enum using a switch is pretty.

  34. Its been my experience that by TheSkepticalOptimist · · Score: 0

    The people that worry about coding style don't write good code. It might look nice, but is fundamentally they don't spend enough time on functionality.

    I have found consistently that the big office blowhard developer that sends out numerous emails and writes documents about the company's coding style practices is typically the person who is the worst programmer in the bunch. He only writes beautifully coded bugs.

    --
    I haven't thought of anything clever to put here, but then again most of you haven't either.
    1. Re:Its been my experience that by Anonymous Coward · · Score: 0

      Is that you, Eric? How many times do I have to tell you, don't write all your code on a single line with 100 ;'s in it and don't call all your variables ericsBaby1, ericsBaby2, ... On a serious note, if you are not thinking about your coding style and practices as a way to reduce the bug count, you're missing a tool in your belt that could make you a more skillful developer.

    2. Re:Its been my experience that by Anonymous Coward · · Score: 0

      Perhaps but since I'm that kind of a coder, I can also quickly debug code or add additional functionality because I know what each curly bracket does - because it lines up with the other brackets and there's a handy comment next to it. That's better than seeing this:
      }
      }
      }
      }

      How many of you have seen that and thought to yourself: let's see, 1... 2... 3...4... yep, that's close enough. If so, I pity the people you work with.

  35. Re:Else ifs - yuck by DdJ · · Score: 1

    Very often rules about efficiency like this one are incorrect.

    In particular, they're very often incorrect today, with modern compilers, even if they were true in the very early days.

    Many years ago, a co-worker offered to teach us PDP-11 assembly language strictly in order to understand the design of C better. If you've got time, it's a worthwhile exercise. A lot of the design of C makes more sense if you understand how bloody simple a compiler for the PDP-11 could be.

    "C combines the power and speed of assembly language with the portability and ease-of-use of assembly language."

  36. Re:Else ifs - yuck by Deltaspectre · · Score: 1

    Ouch, and I thought my reply might have been a little harsh. Way to go Slashdot.

    --
    My UID is prime... is yours?
  37. Re:Else ifs - yuck by Anonymous Coward · · Score: 0

    >OO enthusiasts have a distaste for both else-if's and case statements, seeing either as a candidate for subclassing and virtual functions.
    I see that as a chance to use MPL and CRTP

  38. subjective by TsuruchiBrian · · Score: 1

    This is a perfect example of why code beauty is subjective. On the one hand the author loves saving vertical space by not putting parentheses on their own lines, then he hates it when you remove them entirely, even though it saves even more space. He finds conditionals without parentheses to be less readable. I find non-horizontally aligned parentheses less readable, and have no problem following conditionals without them.

    I think where it becomes less arbitrary (but still subjective) is in the actual design. I don't see the point of not using STL. Being able to write 1 hash (or use someone else's) without needing multiple copies in the code simply to deal with different types seems great to me. Yeah it's a little harder to read, but you only need to read one of them, and you know all the hashes are the same unless there are methods overloaded for different types. Checking that each part of 2 classes that look identical except for types, are actually identical is tedious.

    Sometimes there is a tradeoff between code readability and design. I tend to favor design over readability. Inheritance makes code less readable, but if done correctly, it makes the design much better by reducing redundant code. Redundant code may be perfectly readable, but it makes it much harder to "read" the design of the application.

    1. Re:subjective by UnknownSoldier · · Score: 3, 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

    2. Re:subjective by TsuruchiBrian · · Score: 1

      OOPS I meant to say C++ tempates, not STL. I actually use QT for pointers and data structures, etc, when I can.

    3. Re:subjective by Anonymous Coward · · Score: 0

      Well, having parens on the same line saves space, but leaving them out can cause bugs so it has a lot more effect than simply saving space.

    4. Re:subjective by UnknownSoldier · · Score: 1

      Minimal templates = OK
      Excessive templates = potential code bloat -- check the linker .map file to tell what is being inlined and what isn't.

    5. Re:subjective by TsuruchiBrian · · Score: 1

      Excessive anything is bad. It's good to use templates whenever you find yourself copying and pasting a bunch of code over and over again, and doing find replace for the types. When you find yourself putting in a bunch of special cases for different types in your "generic" code, then maybe it's time to take the templates out.

    6. Re:subjective by Anonymous Coward · · Score: 0

      Code bloat

      This isn't 1992. You can spare a few kilobytes for that template code.

      hard to debug

      Once again, not 1992. Debuggers have caught up and now parse STL containers.

      no way to serialize...

      Welcome to everything in C++. Unless you mean binary dumps, in which case have fun with the version management nightmares.

  39. Re:Else ifs - yuck by ShanghaiBill · · Score: 1

    there wouldn't even be a difference in generated assembler, let alone performance.

    Not necessarily. If there are enough cases, a switch statement will be faster because the compiler will create a jump table. But an if-else chain will be faster if the programmer knows (and the compiler doesn't know) which cases are more common, and tests for the most common cases first. But in most cases it doesn't matter. So use whatever makes the code more readable.

  40. Re:Else ifs - yuck by blueg3 · · Score: 3, 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.

  41. you're obviously not a game developer by Anonymous Coward · · Score: 1

    As an engine programmer at one of his competitors, I can assert that I completely agree with all of his opinions, especially "if it needs comments, it should probably be re-written" and "const everything as possible". Also we use our own STL-like containers, we don't use an off-the-shelf STL implementation because most of them are more bloated than we would like on consoles (e.g. too much inlined code)

  42. Re:Else ifs - yuck by willy_me · · Score: 2

    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 always obvious. You have to look at each case individually. But for desktop programming, one should use the syntax that results in the most readable / understandable code. Desktop compilers are good and should be able to optimize the result. The impact of one over the other will not be noticed 99% of the time - while the difference will impact code maintenance 100% of the time.

  43. Re:Else ifs - yuck by Anonymous Coward · · Score: 0

    Not precisely.

    http://en.wikipedia.org/wiki/There_are_known_knowns

  44. to restate the advise: by RobertLTux · · Score: 1

    always give enough comments to ensure that a drunken idiot programmer could understand what is going on

    (of course in 4 months you might BE said DIP ...)

    --
    Any person using FTFY or editing my postings agrees to a US$50.00 charge
  45. Re:Else ifs - yuck by Anonymous Coward · · Score: 1

    You're thinking of GOTO statements

    kidding

  46. Re:Else ifs - yuck by Anonymous Coward · · Score: 0

    This depends wholly on the size of the case statement.

  47. Re:Else ifs - yuck by X0563511 · · Score: 1

    I know lots of things I don't know.

    Rather, I know that I don't know them.

    (head: asplode)

    --
    For large sets, this will be our guide even unto death, for the LORD will work for each type of data it is applied to...
  48. Re:Else ifs - yuck by Jmc23 · · Score: 1
    Well, we all look forward to your analysis of speed with the original code and where you replace else-if with case.

    What, you don't plan on doing that? So why should we take the word of some unknown person over Carmack?

    --
    Don't complain about syntax, grammar, or spelling. There is no.hell like input on android.
  49. Re:Else ifs - yuck by gander666 · · Score: 1

    Gah, I learned PDP11 assembly back in college (yeah, I am that old).

    --
    Suppose you were an idiot and suppose you were a member of Congress ... but I repeat myself. - Mark T
  50. Re:Else ifs - yuck by Joehonkie · · Score: 1

    Wait, so if I don't have the junk in the boot, painting it red DOES make it go a little faster?

  51. You asked for it. by Dan+East · · Score: 4, 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.

    --
    Better known as 318230.
    1. Re:You asked for it. by vux984 · · Score: 2

      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.

    2. Re:You asked for it. by Anonymous Coward · · Score: 0

      switch (dot < -LIGHT_CLIP_EPSILON) {
              case TRUE:
                      sides[i] = SIDE_BACK;
                      break;
              case FALSE:
                      sides[i] = SIDE_FRONT;
                      break;
              case FILE_NOT_FOUND:
                      sides[i] = SIDE_ON;
      }

    3. Re:You asked for it. by SourceFrog · · Score: 1

      I've seen much worse things in production code.

      --
      My other UID is three digits.
    4. Re:You asked for it. by Anonymous Coward · · Score: 0

      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.

      Because slashdot's commenting code hasn't been improved since Clinton was in the white hose.

    5. Re:You asked for it. by lewiscr · · Score: 1

      Tri-state booleans FTW.

    6. Re:You asked for it. by lewiscr · · Score: 2

      ...since Clinton was in the white hose.

      I don't remember that part of the Lewinski scandal.

    7. Re:You asked for it. by smallfries · · Score: 1

      You haven't actually represented it as a switch-case. As the other commenter points out you have tacked a redundant switch-case onto the code:

        sides[i] = dot < -LIGHT_CLIP_EPSILON ? SIDE_BACK : dot > LIGHT_CLIP_EPSILSON ? SIDE_FRONT : SIDE_ON;

      CS instructor eh?, wouldn't let you cover my class for me... :)

      --
      Slashdot: where don knuth is an idiot because he cant grasp the awesome power of php
    8. Re:You asked for it. by Anonymous Coward · · Score: 0

      Actually the x86 has conditional statements that aren't used for jumping, for example an 'assign-if-equal'. A good compiler will figure out when to emit such statements with a ? : . A better compiler could infer that those if statements should also yield those non-jump conditional statements.

    9. Re:You asked for it. by czth · · Score: 1

      Brillant!

  52. Re:Else ifs - yuck by Anonymous Coward · · Score: 0

    I know some situations else-if statements are necessary, but my understanding is that case statements are far faster. So this "beautiful code" perhaps should have focused on code that could process faster as if this is one mistake in efficiency, wonder what else ID missed?

    Readability is good and usually it doesn't hurt performance too bad. I often find myself looking for an elegant solution to a given problem, and when I find it, it's usually both readable and efficient. Switch statements (or case statements if you prefer) are useful when you have a single expresson to be evaluated against multiple constants, but not so much when you have multiple different expressions as in the example code in the article.

    John Carmack and id software essentially pioneered 1st person shooters and likely seeded the demand for ever more detailed graphics which in large part help give rise to the graphics software (games) and hardware (engineers motivated by the gaming industry) we see today.

    Questioning their ability to produce efficient code without arguments to back it up is silly at best.

  53. Beautiful = Performant in this case by cplusplus · · Score: 1

    Half the 'beautiful' styling mentioned in the article (minimal use of templates, getter/setters, etc) leads to code that executes faster, without relying on compiler optimization to fix it up later.

    --
    "False hope is why we'll never run out of natural resources!" - Lewis Black
  54. Re:Else ifs - yuck by Anonymous Coward · · Score: 0

    case statements are faster O(1)

  55. you guys are just bots, not alive... by zugedneb · · Score: 0

    if you had any understanding of what you are talking about, you would say that the difficult and important things are to choose the data structures for you problem, to design the function that renders the model in multiple threads, to design the interthread communication and so forth... you would say, the beauty lies in the architecture... instead you just come with your sad shit about what language is better then what other... you are just poorly programmed bots, made by a second rate god apprentice...

    1. Re:you guys are just bots, not alive... by phantomfive · · Score: 1

      I'm not sure you know what you're talking about.

      --
      "First they came for the slanderers and i said nothing."
    2. Re:you guys are just bots, not alive... by uninformedLuddite · · Score: 1

      Liberal arts students can program too you know

      --
      The new right fascists are bilingual. They speak English and Bullshit.
  56. LOLL by Anonymous Coward · · Score: 0

    to bad it runs like shite..

    I remember trying to use solaris once - this was at the end of sun's lifecycle. The updater told me there was like 20 critical patches I needed to install post first install. Every single time I tried updating the critical security patches Solaris would just up and die. A complete reinstall of the OS was required just because the buggy security patches not working. I did this 3 times thinking it was a fluke. (solaris 10 out of the box). Eventually I just said fuck it and ran solaris without any updates. I come to later find out to even get patches I needed a 'support contract' - yes they were charging for critical security patches. All of this pain just to use ZFS.. (at the time)

    It can look wonderful. Hell I can write a program to generate a bunch of random code that "looks good".. it's so beautiful... But how the fuck does it run? In doom's case the game ran great AND the code looked good. In solaris's case, the code probably just looked good..

  57. iD by Khashishi · · Score: 2

    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.

  58. Re:Else ifs - yuck by tepples · · Score: 1

    It's just a matter of whether or not the optimizer can figure that out.

    And when taken to the extreme, people like StoneCypher have criticized me for my choice of a tool that I could afford. The comment was to the effect "Please stop bad-mouthing certain C++ constructs just because GCC optimizes them poorly. Instead, try this $6000 Green Hills compiler with a better optimizer."

  59. BS this is how it looked during development by TheSkepticalOptimist · · Score: 2

    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.

    --
    I haven't thought of anything clever to put here, but then again most of you haven't either.
  60. Re:Else ifs - yuck by tepples · · Score: 1

    Many years ago, a co-worker offered to teach us PDP-11 assembly language strictly in order to understand the design of C better. If you've got time, it's a worthwhile exercise.

    That or VAX assembly or 68000 assembly, as they appear to have been designed by PDP-11 fans.

  61. Re:Else ifs - yuck by sympletun_1997 · · Score: 2

    To expand upon your final point: The real reason to use switch vs else-if is in what you communicate to other programmers. Switch communicates that you're evaluating exactly one variable/operation. Else-if towers can mix and match the evaluation criteria. Programmers who choose an else-if tower for evaluating the same variable all the way through are just inviting trouble in the future, when someone comes along and adds an additional clause to one of the evaluations and screws the whole thing up. Oh also, some compilers have a maximum number of else-if conditions. I worked at a company that created a huge else-if tower which eventually grew too large and broke MSFT's cl. We quickly rewrote the code as a hashtable (which is what it should have been anyway).

  62. Re:Else ifs - yuck by blueg3 · · Score: 1

    In practice, you can't take it to too much of an extreme, because optimizers are not arbitrarily smart. Programmers also often don't bother to hint to the optimizer their assumptions and requirements.

  63. Fairly ugly by loufoque · · Score: 2

    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...

    1. Re:Fairly ugly by Anonymous Coward · · Score: 0

      The linux kernel is mediocre. Read Plan9's.

    2. Re:Fairly ugly by Indigo · · Score: 1

      +1 for that. Plan 9's code, written in C, has a clean, minimalist aesthetic throughout that makes it dead easy to navigate, skim, or analyze in depth. Files, lines, and functions all tend to be short. Code within functions is often times linear with simple conditionals or loops; there's still complex logic to be found, but far less than other software; more than 4 levels of indentation is uncommon. Even the makefiles are simple and clean.

      File, type, and function names are usually short and unambiguous. Variable names average 1-2 letters: r for Request, f for File, to and from for strings. Comments are used sparingly; when present, they give you the salient facts without unnecessary detail. They, too, are mostly short, but longer where more explanation is called for.

      With all this brevity, you might expect the code would be cryptic or cramped, but it is extremely easy to follow, with a very "clean" and "natural" feel - easy on the eyes, with plenty of space. You can dive in at any random point and easily understand what is going on and why.

      One may, of course, argue that the limited number of hardware platforms supported (half a dozen or so?) and operating systems (one) freed the authors from a huge amount of complexity and allowed them to keep their code simple. Could be. gcc's headers make my eyes bleed, but between POSIX and portability to every hardware and OS known to humanity, it's hard to fault them for it.

      Overall, Plan 9's code is the cleanest, the easiest to understand, and possibly the most "beautiful" that I've seen.

    3. Re:Fairly ugly by TheMathemagician · · Score: 1

      Couldn't agree more and surprised I had to scroll down this far to find such a view. The code is OK but with a variety of annoying things wrong. I write more beautiful code than that at work every day. I had my doubts when the author wrote that "MainMenu.cc ballooned to 24,501 lines. The once-beautiful source code was a mess riddled with #ifdefs, gratuitous function pointers, ugly inline SIMD and asm code". To a guy living in a mental pigsty the id code would look pretty nice but it's far from beautiful.

    4. Re:Fairly ugly by loufoque · · Score: 1

      I write SIMD code everyday (I work in numerical computation optimization), and it's still quite pretty.
      I did write some C++ library to make it prettier though.

  64. Comments are bad? by Digital+Vomit · · Score: 3, Funny

    "Comments should be avoided whenever possible. Comments duplicate work when both writing and reading code."

    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?

    --
    Modern copyright is theft of culture from everyone and it retards the progress of the useful arts and sciences.
  65. The things he likes are the things I hate by Dixie_Flatline · · Score: 4, 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.

    1. Re:The things he likes are the things I hate by hibiki_r · · Score: 1

      Yes, English beats random code, but comments can get outdated very easily. One of the worst things that can happen when trying to maintain a piece of code is to see out of date comments that don't really reflect what the system is doing. All it takes is someone to create a comment that spends time describing a dependency, or just someone that fails to remove a comment that isn't valid anymore. At that point, the comment lies. I'd much rather be told nothing that lies.

      Now, since English is very valuable, that's why we just use English in ways that will not betray us. Unit tests tend to lie very little, and aren't hard to name well in most frameworks. You can also automate bigger tests using something like Cucumber, and then know when the specs aren't being met: If the story fails, there's a good chance that what it says isn't true anymore. You can then either fix the code to make the spec pass again, or update the spec. Either way, no more lies.

    2. Re:The things he likes are the things I hate by dkf · · Score: 1

      Yes, English beats random code, but comments can get outdated very easily.

      If your comments are getting outdated easily, you're probably writing the wrong comments. Comments should be for information that is not obvious in the code (e.g., which bug report IDs are related, which journal has the paper that you cribbed the algorithm from) or that is not going to go out of validity easily (e.g., /* check preconditions */ is reasonable, even if a little obvious, because it is still a higher-level concern that doesn't go out of date rapidly. You don't normally need to describe how you're doing the checking though, as the machine-readable part of the code says that and ought to be clear.)

      --
      "Little does he know, but there is no 'I' in 'Idiot'!"
    3. Re:The things he likes are the things I hate by drinkypoo · · Score: 1

      Yes, English beats random code

      Straw man, the word "random" appears nowhere in the parent. If you have apparently random code in your code, you should check for the presence of AI, because Skynet is probably coming. That, or you're having a problem with your filesystem or storage driver.

      --
      "You're right," Fisheye says. "I should have set it on 'whip' or 'chop.'"
    4. Re:The things he likes are the things I hate by 14erCleaner · · Score: 1

      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.

      I was agreeing with you completely until this. Putting your name and the date in code is useless. Your version control system should tell you who did what and when, littering the code with your name is just ego. When a programmer leaves, do you go through and remove his name from all the code?
      On a similar topic, comments should be "absolute", not "relative". By this I mean that you don't comment the change you made to the code, you comment what the code does now. I don't care when you changed it, the version control system can tell me that. If there's some tricky coding that was inserted to fix some bug, explain what you're doing, but don't bother telling me what it used to do.

      --
      Have you read my blog lately?
  66. Re:Else ifs - yuck by TheNinjaroach · · Score: 3, 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.

    --
    I went to eat some animal crackers and the box said, "Do not eat if seal is broken." I opened the box and sure enough..
  67. Re:Else ifs - yuck by Anonymous Coward · · Score: 0

    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 subclassing and virtual functions.

    I personally really dislike this. I think it makes the code HARDER to read, because you have things like this... assume you have an interface "Combiner" which combines two values in some way...


    Combiner combiner = new CombinerMethodA(); // or CombinerMethodB, C, ... ...

    combinedValue = combiner.combineValues(valueA, valueB);

    The problem is, at that point of the code, I have no idea which combiner method was chosen... now I have to search for the declaration just to figure that out. If someone else changes it and I didn't realize, I might spend quite awhile trying to debug an issue until I realize what happened.

    The other way:


    combinedValue = combineValues(valueA, valueB, COMBINE_METHOD_A);

    is clear immediately. If the method is chosen by the user, there's not really any particular advantage to either...

  68. Disappointing analysis. by ravyne · · Score: 2

    Came hoping to learn what's so beautiful about iD's code, left convinced that the author (Shawn McGrath) and I have rather different opinions on that... iDs code is certainly not an example of poor code, in a previous job I had the opportunity to view code from around 20 different AAA game studios, its definitely in the top quarter (but that's not saying a great deal); mostly the article is 50 paragraphs of cooing "iD does what I do, guys!" Analysis of what makes said style "beautiful" is subjective at best, and furthermore the author describes himself as "not a coder". For what its worth, IMHO, the best code that I've seen came out of Remedy.

  69. Fantastic article, and from Kotaku? Impressive. by twocows · · Score: 2

    I normally hate most of the garbage that comes out of Kotaku, but this is a really good article. That said, it reminds me a lot of Yossi Kreinin's C++ FQA. A good chunk of the article is spent talking about how Doom 3's source is good code despite being bad C++. What kind of language is best written in a way frowned on by the C++ community? Absurd!

    1. Re:Fantastic article, and from Kotaku? Impressive. by Vreejack · · Score: 1

      Thank you for the reference to Yossi Kreinin. I taught myself C as a child and later learned C++ from Scott Meyer's books (which should have been a red flag--learning a language by studying its workarounds) but I had never seen Krenin's FQA before. I had no idea that all the stupidity of C++ was not considered normal or necessary in computer science.
      I think I must have quit programming right after learning loki, because I must have instinctively understood that a language extension that uses idioms that are completely orthogonal to the base language (recursive vs iterative) is INSANE.

      And here it is twenty-some odd years later and std::cout is STILL slower than printf() despite the latter being type-determined at run-time.

      Anybody using D?

      --
      "Will future ages believe that such stupid bigotry ever existed!" -- Ivanhoe
  70. Re:Else ifs - yuck by jomama717 · · Score: 2

    I always code for a single return statement at the end of a function but not for performance reasons, I just think it is easier to eyeball. I don't care what the compiler does with it. I hate trying to eye-debug a method/function that is peppered with return statements (aside from maybe a single "guard" statement at the top of the function), I inevitably miss one and go trundling down the wrong path, wasting a bunch of time in the process. My functions typically all end with "return retVal;" YMMV

    --
    while [ 1 ]; do echo -n -e "\xe2\x95\xb$((($RANDOM&1)+1))"; done
  71. "const nazi" by Quila · · Score: 1

    One of my early CS professors for sure. Not one number could be found in your code. If you wanted to divide by 2, you'd better have a const up top defined as 2 and then use it.

    1. Re:"const nazi" by phantomfive · · Score: 1

      That's not the same, that is getting rid of magic numbers.

      Const nazi is usually most easily recognized by declaring method parameters const all the time.

      --
      "First they came for the slanderers and i said nothing."
    2. Re:"const nazi" by spongman · · Score: 2

      he's probably referring more to reference and method 'constness' which have semantic rather than just simply syntactic implications.

  72. 3 rules by Anonymous Coward · · Score: 0

    Code should be locally coherent and single-functioned: One function should do exactly one thing. It should be clear about what it's doing.
    AGREE, though applications with much scoped behavior can become a mess.

    Local code should explain, or at least hint at the overall system design.
    AGREE, it needs to push you to learn the design or hint that there's a design behind it.

    Code should be self-documenting. 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.
    NOT AGREE, you miss the whole encapsulation point. Hence blackbox testing of code and modularity will suffer--yes it will suffer.

  73. Slightly misleading by Hsien-Ko · · Score: 2

    "All id games before Quake III were written in C."

    Fool! Quake III Arena was also written in C.

  74. A Valuable Discussion by Epicaxia · · Score: 1

    It seems like a lot of contributors here are missing the point. Discussions like this--and particularly the analysis that provokes them, regardless of how perfect it may be--are highly valuable and productive, for the same reason as project post-mortems. Too often, debates about development (where it's styling, methodologies, or rules of thumb) are done before coding begins, and as a result, several things invariably happen:

    • * Contributions are made by people with little or no knowledge of the topic
    • * Contributions are made by people with little or no experience
    • * Too much time is spent debating theory and not practice
    • * Minor and unimportant topics absorb the majority of pre-development time and energy
    • * Development planning becomes convoluted, and / or ends of being thrown out as actual development begins and unforeseen issues arise

    This, of course, is a reflection of the principle that a good engineer learns from his mistakes, while a great engineer learns from other people's mistakes. Both pictures and hindsight are worth a thousand pre-emptive, ill-informed words. I'm particularly pleased with the focus on coding quality, which (in post-mortems and hindsight analysis like this) takes second place to project and management practices. I will take, and have learned infinitely more from, 10 /.-ers debating an informed and evidence-based review of a quality codebase over 1000s of discussions about programming theory, the latest development paradigm fad, or some wannabe game designer's blog post.

  75. Re:Else ifs - yuck by s1lverl0rd · · Score: 1

    AFAICT there is no reason that dictates that if-else chains can never ever be optimized to use jump tables. My guess would be that the optimization rarely applies to ifs, and slightly less rarely to switches, which means compilers would only attempt to use jump tables in the second case. Even then there's usually a handful of conditions that must be met before jump tables make sense (there should be relatively few cases, and they should be continuous). 'Most of the time' seems like a bit of an overstatement to me, though I don't have the data to back that up.

    'Much more efficient' should probably be backed up by benchmarks, measurements, citations and the like.

  76. Carmack now a bad joke by Anonymous Coward · · Score: 0

    Once Carmack was a genius. Now he is a bad joke, and the world is filled full of game engines infinitely better than anything Carmack could dream of coding today. The why of this is interesting.

    Doom was a masterpiece of an engine, although it was surpassed in every possible way a little later by the 'build' engine (see 'duke nukem'), the work of another young programmer.

    Quake 1 had a very interesting engine (with Abrash doing much of the important work) but had the misfortune to be badly timed- an engine optimised for software rendering on the cusp of the PC GPU revolution.

    Abrash, of course, went of to do the wonderful software renderer for Unreal (sadly obsolete, since real fans had 3D hardware by the time it was released).

    Quake 2 and 3 (now Carmack's exclusive show) were horrid disappointments, although 3 had an interesting, if very limited, tessellation system for curved surfaces. However, it was Doom 3 that convinced most sane observers that the age of iD was over.

    Rage was an abomination, but also a project that took a ludicrous number of years to complete. The engine is so putrid, Bethesda (the suckers that ended up buying iD) can neither use it internally (on non-iD projects) nor license it out for others to use.

    My point- well it was around the time Carmack started mithering about his code, and issuing public statements about how iD needed to move to C++, and write code according to the methods dictated in Computer Science text-books, that iD went down the drain. When Carmack was a natural coder, assuming his ideas and methods were good, he produced good engines. When he felt embarrassed and uncomfortable with his self-taught methods, and needed to impress 'academic' types with his source (not the finished applications), his output went to hell.

    Now some of you will try to tell me 'academic' code is essential in this case, because others needed to use and support his code. WRONG! It was when Carmack started to code this way that his engines became less and less desirable for others to license. Contrast this with Epic, and their Unreal engine. The Unreal engine ended up inheriting the entirety of iD's early success.

    Carmack's last two 'technologies' were useless. The dreadful shadow system in Doom 3 set back shadows in games for years, because the method was so ill conceived. The constantly streaming textures in 'Rage' gave us some of the worst texture work ever seen in a supposedly AAA title. While Carmack's streaming made midground images look great (mostly) foreground and background textures looked like total lo-res crap. Worse, the production pipeline for artists on this engine was the least efficient ever invented, and led to artists simply replicating the same texture over and over into the megatexture, and then smearing a few pixels so Carmack could claim that ever texture was unique.

    One could argue that Gearbox developed and released Borderlands 1 + 2 (same concept as Rage but far far better execution) to mock iD, and prove how quickly, cheaply and how much better such games could be executed on the Unreal engine.

    Sorry, "My source looks great, and a Computer Science teacher at a third rate university would give me top marks for that" is not a selling point in the games industry, when it is your output that counts.

    Carmack's engines cannot do interiors above average, do exteriors very poorly, cannot handle large regions, cannot handle realistic vegetation, have poor lighting models that are years out of date, and lack good physics. Affection for iD's later work is actually largely affection for the Quake 3 licensed engine, after it had been extremely improved in every respect by other software teams. The work iD couldn't be bothered to do itself, no matter how much money they were raking in from the days when people did license their engine.

    And the Doom3 code we are talking about here. I think only one non-iD team licensed that engine (at a time when iD was desperate for business) for that game with the 'Native American' that is captured can space invaders that some of you might just remember. Yes, that sure was some beautiful code.

  77. Re:Else ifs - yuck by snemarch · · Score: 1

    ...presuming the compiler doesn't convert the if/else-if chain to a jump table.

    If you need this kind of optimization, you're going to be doing such compiler (and version!) dependent programming that you might as well break out your trusty assembler. And when working at assembly code level, you can combine the two - heck, it might even make sense to have a few "cmp/je" for the most used cases, perhaps a binary-search-logic series of branching, and finally some jump tables of the rest. Or perhaps jump tables in the binary-search-logic branches, if your ranges are sparse.

    Hint: profile your code and know what you're doing before you even consider such a thing. And write tools so you don't have to hand-code it.

    --
    Coffee-driven development.
  78. Re:Else ifs - yuck by snemarch · · Score: 1

    Also: profile-guided optimization

    .

    --
    Coffee-driven development.
  79. Re:Else ifs - yuck by plover · · Score: 2

    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 decision exactly one time, at the time you learn the value of the data in the proper context. Then when it comes to the code where you would have put an if/else-if ladder or a switch/case construct, you simply dereference a pointer and are executing the proper logic. Having that one decision point serves you for all future decisions based on that data.

    I mean hey, if you're going to be writing in an object oriented language, you probably ought to be using it.

    --
    John
  80. Re:Yeah... and... by Anonymous Coward · · Score: 0

    Id isn't a game company they make the lionshare of there money selling the game engine, so the code being good was in fact their primary goal.

  81. Nice code or agrees with his style by EmperorOfCanada · · Score: 2

    Much of code is a matter of taste:
    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.

    1. Re:Nice code or agrees with his style by Anonymous Coward · · Score: 0


      if ( x==1 ){
          bla();
      }

      You missed my favorite.

  82. Re:Else ifs - yuck by phantomfive · · Score: 1

    Yeah, whatever is most readable is what I prefer.

    --
    "First they came for the slanderers and i said nothing."
  83. Re:Else ifs - yuck by Anonymous Coward · · Score: 0

    A good compiler will never implement a case statement as a load of if-else's...

    So then it is not a good compiler, because it refuses to use an option that is sometimes faster?

    ... unless the case values are sparse

    Oh, by "never" you meant "not never." You are basically agreeing with the post you are replying to then. Compilers will pretty explicilty state when this "never" condition happens. With GCC at least, it is (or was if I am out of date) if there less than 6 cases, or the cases were sparse in a specific way.

    if-else statements into a lookup table is seldom possible unless the if-elses all compare the same integer variable to a constant.

    So also agreeing with parent poster and others posting similarly? Of course, if you use if-else for more complex comparisons across multiple variables, it won't get converted to a jump table, because it can't (short of programmer doing a really bad job at designing conditions). So what is the point of comparing that situation to using a switch/case if it is not something that can be used that way?

    But when using a chain of else-ifs to compare the same variable to different values (i.e. as another poster said, using something equivalent to a switch statement) it is pretty easy to optimize that into a jump table with the back end of compilers I've worked with. I tested this with two test files in C. I noticed GCC did not turn the if-else blocks into a jump table, while Clang produces too binary identical files regardless if I used a large switch block or if-else chain.

  84. Re:Else ifs - yuck by Anonymous Coward · · Score: 0

    Oh, and I forgot to mention, even in the GCC case, the time difference between the switch and if-else block was a few percent. That was for a switch statement with 10 cases, using a simple linear congruence psuedorandom number as input, and each case did some arbitrary bit twiddling. The equivalent if-else block one that didn't use a jump table was the one that was a few percent shorter. The time difference between the Clang compiled ones was zero... obviously since they were binary equivalent, but a few percent slower than the GCC ones.

  85. Compare and Contrast by Anonymous Coward · · Score: 1

    I work at Google. I find it interesting to compare/contrast the style points in this article with the very thorough style guide at Google. Generally, I agree with Google where they differ.

    Const and Rigid Parameters: At Google, all reference/pointer inputs and all member functions must be const where possible. Local variables do not need to be. I personally find it more hassle than I care to bother with on local variables, but the rest is all or nothing, and I (and Google) agree with him that all is much better than nothing.

    Minimal Comments: Urgh. Yes, there are useless comments out there. There are also way too few useful comments. At the bare minimum, there should be a top-level comment for every class. No exceptions. Ever. And to suggest you should rewrite every piece of code that does something non-obvious or solves a non-obvious problem? Good luck with that.

    Vertical Spacing: Google also uses same-line braces, but it's pretty arbitrary - consistency is the important thing. Anyone who says otherwise is a zealot =). In any case, it's not an excuse to remove all vertical white space.

    Minimal Templates: You should not add templates just for the heck of it, but forcing a hash table to have a char* key is NOT a good thing.

    Get/Set Methods: Public member variables are forbidden at Google. A little boilerplate is deemed a very acceptable tradeoff for controlled mutation.

    Streams: Also not allowed at Google, except for logging. This is not because the syntax is "ugly" though. It's because (a) streams are poorly implemented and are inefficient, and (b) standardization is required. Interesting that John Carmack mentions that misaligned printf formatting is a big cause of bugs - in g++, the compiler catches that. Alas not in VS.

    Operator Overloading: Also forbidden at Google. Honestly though, for all the bugaboo made about these guys, I don't see anyone really abuse them anywhere.

    Horizontal Spacing: Ew? As for tabs, they are outlawed at Google. Editors are configured to replace them with spaces.

    Method Names: Meh. Google generally agrees except for pure accessors. He doesn't have those, so I guess that's agreement.

  86. Re:Else ifs - yuck by Anonymous Coward · · Score: 0

    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.

    You are forgetting "the make the car go faster white stripes"

  87. Robert C. Martin's Clean Code by Ivan+Stepaniuk · · Score: 1

    I bet the author did not read that book.

    --
    My other signature is a car
  88. Re:Else ifs - yuck by Anonymous Coward · · Score: 0

    But instead of searching for "return xyz" you will be looking for "retval = xyz", so you save nothing.

  89. Re:Else ifs - yuck by Sigg3.net · · Score: 1

    Like my math teacher in high school said to a student: Open your mouth less. Open your eyes more.

      (This student argued about everything.)

  90. Re:Else ifs - yuck by gbjbaanb · · Score: 1

    I assume you're talking about C code.

    C#, for example, lets you write a case statement with strings, I don't think that gets implemented as a jump-table.

    Anyway, never underestimate the ability of a compiler to optimize a bunch of if statements (assuming a single variable) into a lookup. If you compare a bunch of if-else statements using different variables in the expression to a single case statement then you're obviously not comparing like with like and sure, if won't be faster except for the case where you match the first if statement. Then I can see if outperforming a switch, and if you can make that call with known data, do it. I wouldn't want the above set of posts to be used to justify someone's stupid coding standards that mandate "always use switch as its faster".

    So all in all, the generic question "is an if-else slower than a switch" is meaningless. If you do refine it it mean something more sensible such as comparing a bunch of if statements using the same integer variable to a case, then it can be faster or slower depending on the data you expect to get and the sparseness of the switch values.

    Ultimately though, even if you're running a million if-else statements, the overall time taken will measured in a few ms anyway. That was my main point, if you're rewriting code to use switch statements "to make it faster" you're going to be disappointed.

  91. Discount Nike shox shoes,Air max shoes sale by aindusvc · · Score: 1

    Hello!!! everybody, Fashion,low price,the good shoping place, click in. ===== ( http://www.sheptrade.com/ ) ===== Discount Air Jordan (1-24) shoes $35, Air max shoes (TN LTD BW 90 180) $36, Nike/shox (R4, NZ, OZ, TL1, TL2, TL3) $35, Handbags ( Coach Lv fendi D&G) $36, T-shirts (polo, ed hardy, lacoste) $20, Jean (True Religion, ed hardy, coogi)$35, Sunglasses ( Oakey, coach,Armaini )$16, Watches(Rolex BREITLING IWC) New era cap $12, Discount (NFL MLB NBA NHL) jerseys, free shipping, Accept credit card payment! ===== ( http://www.sheptrade.com/ ) =====