Skip to main content
Engineering LibreTexts

2.7: Spaces and Such

  • Page ID
    29020
  • Readability

    It may seem a bit picky, but you will be required to use appropriate spaces to improve the readability of your code.

    The two lines of code are the same:

    if(myAgeValue>60 && myCarSpeed>75) {
       myInsuranceRate=i+k/m;
    }
    
    if (myAgeValue > 60 && myCarSpeed > 75) {
       myInsuranceRate = i + k / m;              //Yes - this violates the meaningful variable name rule
    }
    

    Both of these statements are valid C++ code, both will work. The first one is just much more difficult to read, because there are very few spaces in the code. To help those who are having to read the code, and perhaps change it or maintain it, add spaces after every key word, before and after a variable name, before and after any operator (=, <, etc).

    One more...

    There is the issue of parenthesis, they can be your friend, use them to not only make sure the compiler knows what you want but also those looking at the code can be sure you know what you are doing.

       myInsuranceRate = i + k / m;              //Yes - this violates the meaningful variable name rule
       myInsuranceRate = i + (k / m);              //Yes - this violates the meaningful variable name rule
    

    Again - both of these statements work. The mathematical order of precedence says left to right, multiplication, division, addition then subtraction. Put the parenthesis around the division to show that is what you intended to happen first.  Do not simply assume that everyone understands what you are doing.

    It is about being professional and taking the time and effort to write good code that is readable and understandable. After 40 years in the software development world, I know this to be true - and you will find promotions and bonuses easier to come by if you do a few simple things.