{"id":42804,"date":"2018-05-24T12:00:53","date_gmt":"2018-05-24T16:00:53","guid":{"rendered":"http:\/\/shamusyoung.com\/twentysidedtale\/?p=42804"},"modified":"2018-05-24T10:42:59","modified_gmt":"2018-05-24T14:42:59","slug":"unity-week-8-some-thoughts-on-variable-names","status":"publish","type":"post","link":"https:\/\/www.shamusyoung.com\/twentysidedtale\/?p=42804","title":{"rendered":"Unity Week #8: Some Thoughts on Variable Names"},"content":{"rendered":"<p>Like I said over the weekend, <a href=\"?p=42777\">my series on Grand Theft Auto 5 has been delayed<\/a>. But I can&#8217;t bear to leave the Thursday spot blank, so here are some meandering, dashed-off thoughts on the problem of variable naming in C#. To be clear, the problems are mostly with me and not C#. Specifically, switching languages is forcing me to shift my <a href=\"?p=18368\">coding standards<\/a> a little.<\/p>\n<p>For years I worked for a company with a mature (meaning large and resistant to sweeping changes) codebase. In 1993 or so it began as a pure vanilla C project, but sometime around the turn of the century we began migrating to C++ while disrupting the existing code and coding style as little as possible. C and C++ are different languages and the practitioners of each language often have very different ideas about how code should be formatted. Since our codebase was a hybrid, our formatting standards were a slightly strange and anachronistic blend of old and new. Since I used these standards for years, they eventually became part of my personal style. I wasn&#8217;t even really a <em>fan<\/em> of the standards, but after you look at one particular style of formatting for a decade or so, everything else starts to look a little strange.<\/p>\n<p>Let&#8217;s look at an example. <a href=\"?p=42796\">Earlier in the week<\/a> I created a SpaceMarine class. Here is how that class might look in C++:<\/p>\n<p><!--more--><\/p>\n<pre lang=\"cpp\" line=\"1\">\r\nclass SpaceMarine: public Meathead\r\n{\r\n  char* m_name;\r\n  char* m_profane_nickname;\r\n  const bool m_is_dude = true;\r\n  float m_beard_stubble;\r\n  double m_burlyness;\r\n  int m_bullets;\r\n  int m_genades;\r\n  int m_hitpoints;\r\n  int m_armor;\r\n  long m_aliens_killed_with_firearms;\r\n  long m_aliens_killed_with_melee_weapons;\r\n  long m_aliens_killed_with_bare_hands;\r\n  long m_aliens_killed_with_shouting;\r\n  int m_dead_wives;\r\n  bool m_cigar;\r\n};<\/pre>\n<p>Each variable starts with <code>m_<\/code>. This is so you can quickly tell member variable (stuff that belongs to the marine) from other variables. For example, say you&#8217;re scrolling through a great big block of code, looking for something. You come to this section:<\/p>\n<pre lang=\"cpp\" line=\"1\">\r\nif (damage_reduction > 0)\r\n  hitpoints = hitpoints \/ damage_reduction; \r\ntotal_damage += hitpoints;\r\n<\/pre>\n<p>Here we&#8217;ve got three variables bouncing around: damage_reduction, hitpoints, and total_damage. At a glance we can see none of these start with <code>m_<\/code>, which means none of them belong to the space marine, which means this section of code is not making any changes to the state of our poor meathead. I think the variable &#8220;hitpoints&#8221; should probably be renamed to make it clear what is being calculated here (incoming damage would be my guess) but hopefully you get the idea. We can use variable names to give the coder more information about the code they&#8217;re reading.<\/p>\n<p>Note that these standards are all self-imposed! There&#8217;s no external force obliging you to adhere to these. If you wanted, you could make the variable names more verbose:<\/p>\n<pre lang=\"cpp\" line=\"1\">\r\nclass SpaceMarine: public Meathead\r\n{\r\n  int m_belongs_to_space_marine_no_touchy_hitpoints;\r\n  int m_belongs_to_space_marine_no_touchy_bullets;\r\n  int m_belongs_to_space_marine_no_touchy_armor;\r\n}\r\n<\/pre>\n<p>That&#8217;s fine. If anyone else goes to work on your code they might start to hate you a bit on account of all the typing and wasted screen space, but this is just as valid as far as the compiler is concerned. Likewise, you can adopt a super terse style:<\/p>\n<pre lang=\"cpp\" line=\"1\">\r\nclass SpaceMarine: public Meathead\r\n{\r\n  int hp;\r\n  int bull;\r\n  int armr;\r\n}\r\n<\/pre>\n<p>This is functionally the same as the previous code, except it&#8217;s all abbreviations and there aren&#8217;t any style markers to make these variables stand out from variables that exist outside of the space marine. <\/p>\n<h3>Who Cares?<\/h3>\n<p>So if the compiler doesn&#8217;t care, why should the programmer?<\/p>\n<p>A lot of programmers will answer this question by pointing to <a href=\"https:\/\/www.joelonsoftware.com\/2005\/05\/11\/making-wrong-code-look-wrong\/\">this post on making wrong code look wrong<\/a>. We try to design coding standards so that:<\/p>\n<p>1) The standards force you to code in ways that make the code better. (Safer, more secure, more stable, more readable, etc.)<br \/>\n2) Code that does not conform to standards will be really obvious.<\/p>\n<p>The thing is, imposing coding standards will always give you the second thing, even if they don&#8217;t give you the first. Once you spend a few days staring at a particular style of code, things written in a different style will stand out. It will feel &#8220;wrong&#8221;, even if there&#8217;s nothing wrong with it. Imagine if you&#8217;re reading a book and it suddenly switches from single spacing to double spacing, and from justified to flush-left alignment. This will probably grab the reader&#8217;s attention. &#8220;What? Why did the style change? Is this passage a quote? An aside? What&#8217;s going on here?&#8221;<\/p>\n<p>Since you&#8217;re probably going to notice coding style no matter what the style is, you might as well come up with a style that has some utility to whatever sort of problem you&#8217;re working on. <\/p>\n<p>Like I said, my coding style is a bit odd. I dislike some of it but sort of follow it out of habit because changing styles (particularly after being stuck with one style for half your career) is hard. <\/p>\n<p>Having said that, I&#8217;ve always hated the <code>m_<\/code> thing. It&#8217;s an annoying and awkward prefix. On an English keyboard, both m and underscore are typed with the right hand, but one is at the bottom of the keyboard and the other is at the top, one is typed holding down the shift key and the other isn&#8217;t. So once I left my day job I began omitting the m and just start member variables with the underscore:<\/p>\n<pre lang=\"cpp\" line=\"1\">\r\nclass SpaceMarine: public Meathead\r\n{\r\n  int _hitpoints;\r\n  int _bullets;\r\n  int _armor;\r\n}\r\n<\/pre>\n<p>So when I&#8217;m scrolling through code later and I see <code>_hitpoints -= damage<\/code> I&#8217;ll know that _hitpoints belongs to the SpaceMarine while damage does not, and that this code is making a change to the state of the space marine. <\/p>\n<p>Shrug. It&#8217;s not a big deal. Aside from this discrepancy, I&#8217;m still using this odd blend of 90s C and turn-of-the-century C++ style. That&#8217;s not <strong>bad<\/strong> or anything, but when I made the jump to Unity I figured it was time to change things and adopt something more in line with popular standards. <\/p>\n<p>And then everything went to hell.<\/p>\n<p>The problem was that I was trying to develop a coding style before I understood the language. For example: <\/p>\n<p>In Unity, the editor will generate dialog boxes for you. Let&#8217;s say you&#8217;ve got this code:<\/p>\n<pre lang=\"csharp\" line=\"1\">\r\npublic int                  AtlasSize = 1024;\r\npublic float                PixelDensity = 16;\r\n[Range(0,1)]\r\npublic float                NormalDepth;\r\npublic Material             AtlasMaterial;\r\npublic Material             AtlasFoliage;\r\n\/\/Visible here just for debugging purposes.\r\npublic AtlasEntry[]         _library_array;\r\n<\/pre>\n<p>If you make all your variables public like this, then Unity will generate a dialog box for you:<\/p>\n<p><div class='imagefull'><img src='https:\/\/www.shamusyoung.com\/twentysidedtale\/images\/pixelcity2_unity2.jpg' width=100% alt='Note that the labels in the right-side box match the variable names from the previous code.' title='Note that the labels in the right-side box match the variable names from the previous code.'\/><\/div><div class='mouseover-alt'>Note that the labels in the right-side box match the variable names from the previous code.<\/div><\/p>\n<p>You can fiddle with those controls to change the values in your variables. <em>You can even do this while the game is running.<\/em> As someone coming from C++, this is basically sorcery.<\/p>\n<p>The thing is, that dialog is sort of designed around the assumption that you&#8217;re going to use <a href=\"https:\/\/en.wikipedia.org\/wiki\/Camel_case\">CamelCase<\/a> for your variables. So if you&#8217;ve got a variable used to store your favorite pasta, you&#8217;d call it &#8220;FavoritePasta&#8221;. Unity will see the capital letters, realize this is two words, and place a space between them in the dialog for readability. On the other hand if you call it &#8220;_favorite_pasta&#8221;, then Unity will try to clean it up for the dialog, but it doesn&#8217;t quite work. You end up with &#8220;Favorite_pasta&#8221;.<\/p>\n<p>This offended me on an aesthetic level and made it feel like I was doing it wrong. So I adopted a style of using CamelCase for stuff that was supposed to show up in the dialog and _old_school for everything else. But then I learned (through people here in the comments) how to properly use the set \/ get features of C#, and that made me change my variable naming a little. <\/p>\n<p>Also, the underscore doesn&#8217;t play well with the autocomplete features of Visual Studio. This wasn&#8217;t a problem in C++ since my classes weren&#8217;t very complex. But now I&#8217;m using Unity classes with literally dozens of built-in Unity-specific variables. My SpaceMarine<span class='snote' title='1'>To be clear, I&#8217;m not actually doing anything with space marines.<\/span> has _hitpoints and _armor, but also a huge list of things that aren&#8217;t really relevant to what I&#8217;m doing. Starting variables with an underscore screws up the autocomplete and shoves all of my variables to the bottom of the little autocomplete popup. <\/p>\n<p><div class='imagefull'><img src='https:\/\/www.shamusyoung.com\/twentysidedtale\/images\/pixelcity2_unity3.jpg' width=100% alt='I&apos;ve only given this class four or five variables, but it&apos;s inherited a few dozen from Unity, and they all show up inm this popup.' title='I&apos;ve only given this class four or five variables, but it&apos;s inherited a few dozen from Unity, and they all show up inm this popup.'\/><\/div><div class='mouseover-alt'>I&apos;ve only given this class four or five variables, but it&apos;s inherited a few dozen from Unity, and they all show up inm this popup.<\/div><\/p>\n<p>So halfway through this adventure I started using a new style that dropped all underscores:<\/p>\n<pre lang=\"csharp\" line=\"1\">\r\nint favoritepasta;\r\n<\/pre>\n<p>My thinking was:<\/p>\n<p>&#8220;Okay, I&#8217;ll use CamelCase for stuff that shows up in dialogs, all lowercase for variables that are visible outside the class, and _under_score style for stuff that&#8217;s ONLY used internally.&#8221;<\/p>\n<p>But all lowercase is hard to read and occasionally ambiguous. I&#8217;ll see &#8220;marinestop&#8221; and I don&#8217;t remember if it&#8217;s supposed to be &#8220;marines top&#8221; or &#8220;marine stop&#8221;, or &#8220;marines to p&#8221; (whatever p might stand for) and so I&#8217;ll have to stop and go read other code before I understand what this variable is and how its used<span class='snote' title='2'>Turns out it actually stands for &#8220;mari nest op&#8221;.<\/span>. So then I start putting underscores back into variables.<\/p>\n<p>It would be one thing if I <strong>began<\/strong> the project with this style in mind, but since this mess evolved over time it&#8217;s a complete patchwork. I&#8217;ll go back to a bit of code from two weeks ago and get confused because my style has changed completely since the last time I looked at it. I keep thinking I need to do a project-wide refactoring to clean things up, but then I think, &#8220;Bah. This is just a skunkworks. I&#8217;ll throw this code away next week anyhow.&#8221;<\/p>\n<p>This is all normal growing pains of course. I&#8217;ve been looking at bits of code to see what other people use, but nothing has really jumped out at me as &#8220;Oh, this is clearly the best way to do things.&#8221; As before, when I finally settle on a style it will probably be based more on habit than merit.<\/p>\n<p>I am curious how people handle it when they have to use multiple coding styles at the same time. If you&#8217;re involved with two different companies &#8211; or perhaps two different projects at the same company &#8211; then how do you deal with it? Do management types still care about coding style? What styles do you hate but are forced to use?<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Like I said over the weekend, my series on Grand Theft Auto 5 has been delayed. But I can&#8217;t bear to leave the Thursday spot blank, so here are some meandering, dashed-off thoughts on the problem of variable naming in C#. To be clear, the problems are mostly with me and not C#. Specifically, switching [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[66],"tags":[],"class_list":["post-42804","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\/42804","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=42804"}],"version-history":[{"count":14,"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=\/wp\/v2\/posts\/42804\/revisions"}],"predecessor-version":[{"id":42824,"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=\/wp\/v2\/posts\/42804\/revisions\/42824"}],"wp:attachment":[{"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=42804"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=42804"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.shamusyoung.com\/twentysidedtale\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=42804"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}