Write Smart Code
|
When you write source code, the more meaning you can pack in the same number of code lines, the better. The code becomes “less verbose” and more difficult to fathom but to a programmer’s eye, it also becomes more elegant. Below are some tricks which I learned during the courses Game Programming I and II. Most of them aren’t anything special and are probably obvious to an experienced programmer but I still notice a lot of my colleague students still prefer the more “verbose” style. This post is aimed to contrast the two styles by showing how many lines of code you can save should you choose to write more sophisticated code. 1. not using Don’t write bool test; if (test == true) ... if (test == false) ... write instead bool test; if (test) ... if (!test) ... This applies also to conditions in while, for loops, switch statement conditions etc. A similar shorthand can be used when checking whether or not a pointer is null: instead of std::string* name; if (name != nullptr) ... if (name == nullptr) ... write std::string* name; if (name) ... if (!name) ... 2. simplifying statements with bools If you want to switch a
bool test;
if (test)
test = false;
else
test = true;
write bool test; test = !test; Many other similar if-statements involving
float d = ...;
if (d <= 5.0f)
return true;
else
return false;
can be simplified to float d = ...; return d <= 5.0f; 3. wrapping an int variable’s value to a certain range I learned this trick from some code a second-year student has written. We have an array of music tracks It seems logical that You could in principle write this code:
//some looping
music->play(m_songs[++n]);
if (n = m_songs.size())
n = -1;
While the code above is pretty clean and simple, the code below is more compact (two lines less, no if-statement at all): music->play(m_songs[++n % m_songs.size()]); However, the most fascinating thing about the above code is that it exploits the properties of Euclidean division (which results in two whole numbers, a quotient and a remainder). When you divide |