{"id":18500,"date":"2013-01-28T07:09:25","date_gmt":"2013-01-28T12:09:25","guid":{"rendered":"http:\/\/www.shamusyoung.com\/twentysidedtale\/?p=18500"},"modified":"2013-01-28T07:10:21","modified_gmt":"2013-01-28T12:10:21","slug":"coding-style-part-4","status":"publish","type":"post","link":"https:\/\/www.shamusyoung.com\/twentysidedtale\/?p=18500","title":{"rendered":"Coding Style Part 4"},"content":{"rendered":"<p><table   class=\"\" cellpadding='0' cellspacing='0' border='0' align='center'><tr><td><img src='https:\/\/www.shamusyoung.com\/twentysidedtale\/images\/splash_frustrated.jpg' class='insetimage'   alt='splash_frustrated.jpg' title='splash_frustrated.jpg'\/><\/td><\/tr><\/table><\/p>\n<p>And so we come to the end of the <a href=\"ftp:\/\/ftp.idsoftware.com\/idstuff\/doom3\/source\/CodeStyleConventions.doc\" title=\"Line to office document on id Software FTP site\">Office document<\/a> that describes the internal coding conventions of id Software. This last section is pretty non-controversial and so I don&#8217;t have a lot to say about it. But here are the last of my notes, for what it&#8217;s worth&#8230;<\/p>\n<p>As before, the style guide is in bold, and everything else is me blathering.<\/p>\n<p><strong>Variable names start with a lower case character. In multi-word variable names the first word starts with a lower case character and each successive word starts with an upper case.<\/strong><\/p>\n<pre lang=\"c\">\r\nfloat x;\r\nfloat maxDistanceFromPlane;\r\n<\/pre>\n<p>Another holy war topic. <em>How do we name our variables?<\/em> There are a lot of systems. <\/p>\n<p>For years, I heard about, encountered, and put up with &#8220;Hungarian&#8221; notation. That&#8217;s a system where you begin you variable names with a letter to indicate what kind of variable it is:<\/p>\n<p><!--more--><\/p>\n<pre lang=\"c\">\r\nfHealth = 0.0f; \/\/A float\r\niHealth = 0; \/\/ An integer\r\nszHealth = \"Dead\"; \/\/A string\r\n<\/pre>\n<p>I never liked this, and I dismissed it as superfluous, overly verbose, and annoying to type.  I went around saying things like, &#8220;Hungarian Notation is superfluous, overly verbose, and annoying to type. Also it sucks.&#8221; The irony is that I&#8217;ve actually been using Hungarian notation this whole time without knowing it.<\/p>\n<p>What I didn&#8217;t learn until I began this series is that this is not how Hungarian Notation was supposed to work.  This is a misunderstood, <a href=\"http:\/\/en.wikipedia.org\/wiki\/Hungarian_notation#Systems_vs._Apps_Hungarian\" title=\"Systems vs. Apps Hungarian\">bastardized offshoot of the original system<\/a>.  This notation scheme is properly called &#8220;Systems Hungarian&#8221;.<\/p>\n<p>Actual Hungarian Notation &#8211; that is, the system devised by <a href=\"http:\/\/en.wikipedia.org\/wiki\/Charles_Simonyi\" title=\"Charles Simonyi\">the man from Hungary<\/a> himself &#8211; was intended to be a system where the first few letters would describe, roughly, how a variable is used or perhaps in what context.<\/p>\n<p>For an example that applies to me:  I often find myself working with a lot of different coordinate systems. There are local coordinates. (Steve&#8217;s gun model is attached to the hand of his character, which is 0.1 units from his center.) There are global coordinates. (Steve is standing 10m north, 103m west of the world origin.) And screen coordinates. (Steve&#8217;s health bar is drawn 5 pixels from the left edge of the screen.)<\/p>\n<p>I&#8217;ll be dealing with a lot of X, Y, and Z variables, each of them mapped to a particular coordinate system.  If I get confused about what kind I&#8217;m dealing with, I&#8217;ll end up accidentally attaching Steve&#8217;s gun to the world origin instead of his hand, or something similarly absurd. So if I see a variable named &#8220;x&#8221; in the code, I have to wonder which coordinate system it&#8217;s in. To figure it out, I sometimes have to backtrack and read a bunch of code. This sort of review is time consuming and cuts down on the time you&#8217;ll be able to spend on more important things, like arguing over brace positioning and tab sizes. <\/p>\n<p>The solution here is to come up with a naming system that lets you know how a variable is being used.  Perhaps <tt>localX, worldX<\/tt>, or <tt>screenX<\/tt>.  <\/p>\n<p>I actually began doing this on my own during <a href=\"?p=11874\" title=\"Project Frontier #1: Getting Started\">Project Frontier<\/a>. Although, you can find many spots in the source where I didn&#8217;t follow this because I forgot or because the code was borrowed from an older project. When <a href=\"?p=15742\" title=\"Project Octant Part 1: Introduction\">Project Octant<\/a> came along I was a little more careful about it. I&#8217;m pretty sure all of my new code follows this, and the only places where I should see unadorned X and Y values is in legacy code.<\/p>\n<p>It seems to be paying off. I&#8217;ve run into a few situations where the variable name rescued me from a bit of confusion or foolishness.  <\/p>\n<p>This way of naming things is now called &#8220;Apps Hungarian&#8221;. I&#8217;m going to be more intentional about following it in the future. (Systems Hungarian still sucks.)<\/p>\n<p>This goes to show that it&#8217;s sometimes worth reading some of those obscure, jargon-laden, theory-heavy essays on coding. Usually I&#8217;d rather <em>write<\/em> code than follow long debates <em>about<\/em> code, but I could probably stand to pay a bit more attention to theory. <\/p>\n<p><table width='600'  cellpadding='0' cellspacing='0' border='0' align='center'><tr><td><img src='https:\/\/www.shamusyoung.com\/twentysidedtale\/images\/codingstyle3.jpg' class='insetimage' width='600' alt='On the upside, we got you a new monitor so you don&#8217;t need to use that green monochrome one anymore.' title='On the upside, we got you a new monitor so you don&#8217;t need to use that green monochrome one anymore.'\/><\/td><\/tr><\/table><\/p>\n<p><strong>Defined names use all upper case characters. Multiple words are separated with an underscore.<\/strong><\/p>\n<p>I&#8217;ve read my share of code in my lifetime. Code from big companies. Code from small contractors. Code by old timers. Code by college pups. Production code, beta code, prototype code, example code, and legacy code. And I&#8217;ve never seen a codebase where anyone deviated from this rule. This rule is so common and so universal that it feels like part of the language itself.<\/p>\n<p>(Okay, there&#8217;s a debate over using consts or #defines. The id doc doesn&#8217;t get into that, and we already did a few laps around that particular mulberry bush the other day. Let&#8217;s just assume we&#8217;re talking about consts OR #defines, whichever tickles your particular fancy.)<\/p>\n<p>When you&#8217;re coding, you will often need magic numbers. Sure, most of us can recognize the usual suspects like pi, but less famous numbers like 0.017453292 (the number you multiply by to convert degrees into radians) are harder to spot. Your code is going to need a lot of very specific numbers.  The number of milliseconds in a minute. Falling acceleration and terminal velocity in Earth gravity. The number of rounds you can put in a revolver. The aspect ratio of a movie screen. The point size of the default font. Whatever.  <\/p>\n<p>You can just stick the numbers in your code as literals if you want to make people crazy.<\/p>\n<pre lang=\"c\">\r\n\r\nif (drop_distance > 768) {\r\n    damage = 14 * (drop_distance \/ 768);\r\n    if (armor > 0) \r\n      damage *= 0.5f;\r\n    health -= damage;\r\n    if (health <= 0)\r\n        GameOver ();\r\n}\r\n<\/pre>\n<p>You can tell what this code does, but the magic numbers make it a little harder to sort out. By using #defines <\/p>\n<pre lang=\"c\">\r\n#define PLAYER_HEIGHT     768\r\n#define FALLING_DAMAGE    14\r\n#define ARMOR_PROTECTION  0.5f\r\n\r\nif (drop_distance > PLAYER_HEIGHT) {\r\n    damage = FALLING_DAMAGE * (drop_distance \/ PLAYER_HEIGHT);\r\n    if (armor > 0) \r\n      damage *= ARMOR_PROTECTION;\r\n    health -= damage;\r\n    if (health <= 0)\r\n        GameOver ();\r\n}\r\n\r\n<\/pre>\n<p>Now we can see what that number 768 is all about.  That's how tall the player is.  Now we can see that you take 14 points of damage for every body length you fall. Even better, if you need to change something later - like perhaps someone says the player should be 640 units tall instead of 768 - you'll just need to change it in one place. Contrast this with the the first case, where you would need to change all instances of 768 to the new value. If you miss some, then you'll have this strange bug where the game has differing ideas about how tall you are based on what it's doing.  Sure, you can use find & replace, but just wait until you have two magic numbers with the same value.  Congratulations, you just made the player shorter but also changed the number of bullets they can carry from 768 to 640. Oops.<\/p>\n<p>Having words in ALL_CAPS with underscores is almost universally understood to mean \"this is a #defined value\".  Seeing this spelled out in the id Software guide is like seeing a \"All employees must wash hands before returning to work\" sign in the scrub room where everyone gets ready for surgery. <em>Yes, I would hope this is the case, but I'm kind of alarmed that it needed to be said.<\/em><\/p>\n<h3>Wrapping Up<\/h3>\n<p>So that's the guide. I'll say that the document  strikes me as being very general, brief, and relaxed.  I've seen longer and much pickier guides at smaller companies. Then again, I've never worked anywhere that could boast of having id Software-level employees. I suppose in a place like that they can give the programmers more liberty.  After all, the rules are supposed to guide you, not hamstring you.<\/p>\n<p>I'm guessing that these style guides are also more detailed when they come from larger companies. (I'll bet Microsoft has many guides that approach novella size.) The larger your team, the more important it is to enforce a rigorous system. Two programmers can quickly learn to spot and accept each other's eccentricities and habits.  On a twenty person team, all those little \"personal touches\" can seem like chaos. <\/p>\n","protected":false},"excerpt":{"rendered":"<p>And so we come to the end of the Office document that describes the internal coding conventions of id Software. This last section is pretty non-controversial and so I don&#8217;t have a lot to say about it. But here are the last of my notes, for what it&#8217;s worth&#8230; As before, the style guide is [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[66],"tags":[],"class_list":["post-18500","post","type-post","status-publish","format-standard","hentry","category-programming"],"_links":{"self":[{"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=\/wp\/v2\/posts\/18500","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=18500"}],"version-history":[{"count":0,"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=\/wp\/v2\/posts\/18500\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=18500"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=18500"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=18500"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}