C++ Tutorials

Writing Professional Code in C++

Good morning, Good afternoon or Good evening accordingly, at whatever time you visit this blog. So many beginners at this point of time might be confused that what is a professional code :P. Well, to be honest, inside every programmer lies a poet and every line or statement of his code reflects the amount of professionalism he possesses. A professional code is something which is definitely easy at the eye and every single line clearly specifies what the programmer intends to achieve via the piece of code.

Style is more than a matter of aesthetic interest. A professional code shows a consistency from start to end, thus making it easier to debug or extend further. Honestly, throughout my entire life, I have not been able to write, what the programmers call as a “Professional or Beautiful Code”. But trust me, a beautiful code presents your approach, more professional, realistic and clear in front of others and that is for what you get appreciated, be it your team, the successor employee, boss and the whole industry as well.

Why should I write professional code?

Consider a scenario, where you are working in a team developing a game of football. A team consists of 5 sub-teams. Each sub-team is provided with a particular objective to accomplish.

  • Team1 writes the code for shooting the ball and the projectile in which the ball will be travelling after the shot is taken.
  • Team2 writes the code for a goalkeeper who intends to save, shoot and dive.
  • Team3 writes the code for climate effects in the match.
  • Team4 writes the code for the formation of teams.
  • Team 5 writes the code for the behavior of players at every moment of the match.

Now suppose you work in Team1 and you need to write the function for kicking the ball. Your function’s input will be the player who is kicking the ball, the skill level of the player and the type of climate. You write 500 lines of code for kicking the ball and return the position where the ball will land and whether the ball is successfully hit or not. A colleague of yours in Team1 is writing the function for the amount of deflection or swing in the ball and also determining whether the ball is intended to be shot at the goal and returns the graphic position of the ball in the air space and the whether the goal has been achieved or not. Suppose he writes 250 lines of code in his function.

A colleague of yours in Team5 is writing the function for the behavior of player after he scores the goal. The input of the function is dependent on the output of the functions written by you and your colleague in Team1. Now, if he encounters a problem due to a fault in your code, he tries to analyse your code and at this point of time, if your code is self-explanatory or beautiful, he might find out the problem and report it to you accordingly.
Now, in future, suppose if you leave your company, while you were engaged in the project and a new lad is hired in order to deal with your code and extend it further as per the requirements of the project.

If your code is very much noob or unprofessional, he will end up not only scratching but banging his head on the desk. At the end of the day, instead of respect++ for your professionalism and expertise, you will be receiving loads of slangs 😛 . Competitive coding also demands beauty in your code so that your teammates can understand the algorithm in a short span of time by the overview of your code. So, to avoid such situations, I bring to you, certain points which will help you to code in a lovely manner –

  1. Maintain the indentation or what we call as “Indent Style”.
  2. Sensible or Meaningful names of any component or module.
  3. Most important “Comments” and “Documentation”.

Indentation Styles

If your code follows a certain design structure or pattern, a form of symmetrical behavior sets up inside the mind and psychologically everybody loves to see symmetry in any object. So, in order to achieve this, we have got certain styles which you can follow in order to beautify up a certain code. But do no end up mixing these styles in the code which will ultimately lead to make your code more worse than it was. 😛

  1. The Allman Style – The Allman style (proposed by Eric Allman) uses broken brackets. The code written in Allman style is as follows –
    int topcode1(int a)
    {
    	if(a==1)
    	{
    		cout<<”Hello World”:
    		return 20;
    	}
    	else
    	{
    		cout<<”Hi World”;
    		return 10;
    	}
    }
    

    I am a fan of the Allman’s Style because every line is vivid and tend out to be more spacious and free. 😀

  2. The Java Style – The Java style uses attached brackets. The code written in Java style is as follows.
    int topcode2(int a) {
    	if(a == 1) {
    		a = topcode1(5);
    		return 10;
    	} else
    		return 20;
    }
    
  3. The KR Style (Kerninghan-Ritchie) – Kerninghan and Ritchie Style uses linux style brackets. Opening brackets are broken from namespaces, classes, and function definitions. Brackets are attached to everything else including statements within a function, arrays, structs and enums. When you stick to KR style, each function has its opening brace at the next line on the same indentation level as the signature of the function at a line of its own. The blocks inside a function, however have their opening braces at the same line of the statement which drives the entire block.
    int topcode3(int a)
    {
    	if(a == 1) {
    		a = topcode2(5);
    		return 10;
    	} else
    		return 20;
    
    }
    
  4. The Stroustrup Style – The Stroustrup Style( a variant of KR style) breaks brackets from function definitions only. Brackets are attached to everything else including namespaces, classes, and statements within a function, arrays, structs, and enums. This style frequently is used with an indent of 5 spaces. The else statement does not forcefully embrace the statement at which the braces of ‘if’ ends.The code written in Stroustrup Style is as follows:-
    int topcode4(int a)
    {
    	if(a==1) {
    		a = topcode3(5);
    		return 10;
    
    	} else
    		return 20;
    }
    
  5. The Whitesmith Style – Whitesmith style uses broken, indented brackets. Switch blocks and class blocks are indented to prevent a ‘hanging incident’ with following case statements and C++ access specifiers (public, private protected).
    int topcode5(int a)
    	{
    	if(a==1)
    		{
    		a = topcode4(5);
    		return 10;
    		}
    	else
    		return 20;
    	}
    
  6. The Visualization Toolkit Style – The VTK style uses broken , indented styles, except for the opening bracket. Switch blocks are indented to prevent a hanging indent with following case statements.
    int topcode6(int a)
    {
    	if(a==1)
    		{
    		topcode5();
    		return 10;
    		}
    	else
    		return 20;
    }
    
  7. The Horstmann Style – Horstmann style uses “run in the same statement” open braces. Switches are indented to allow a run-in to the opening switch block. This style is frequently used with an indent of 3 spaces. This style includes the advantages provided by Allman by making the margin of the alignment uniform vertically and saving of the line which was the feature of KR style.
    int topcode7(int a)
    {	a = topcode5(1);
    	if(a==1)
    	{	printf(“Hello”);
    		return 10;
    	}
    	else
    	{	printf(“Hi”);
    		return 20;
    	}
    }
    
  8. The Pico Style – The Pico style is quite different from the above mentioned styles because of the fact that in “Pico programming Language” there are no return statements and semicolons have the work of separating the statements instead of terminating them. Opening braces are broken and allow run-in statements. The closing braces are along with the last line in the block. Switches are indented to allow a run-in to the opening switch block. This style frequently is used with an indent of 2 spaces. So in the case the code will have the following structure.
    void topcode8(int a)
    {	a = topcode6(1);
    	a = topcode5(2); }
    
  9. The Ratliff Style – The Ratliff Style also known as the banner style , is analogous to 1TBS style in the way it starts. The style makes it easier to analyse the stuff visually, since the headers of any block are the only thing extended at that level. It uses attached and indented brackets.
    int topcode9(int a) {
    	if(a%2) {
    		a = topcode7(1);
    		return 10;
    		}
    	else {
    		a = topcode8(2);
    		return 20;
    		}
    	}
    	}
    
  10. The 1TBS style – The One true Brace style( a variant of KR style). The main point which distinguishes it from the the other styles is that the one line conditionals also need to be enclosed in braces. An example code to demonstrate the fact is as follows:-
    int topcode10(int a)
    {
    	if(a%2)   {
    		a = topcode8(1);
    	} else   {
    		a = topcode9(2);
    	}
    }
    
  11. The GNU style – The GNU style combines the Allman and WhiteSmith style by putting braces on line by themselves, and indentation of two spaces, except when opening a function definition, where thery are not indented.
    int topcode11(int a)
    {
    	if(a%2)
    		{
    			a = topcode9(1);
    			a = topcode10(2);
    		}
    }
    
    

So, these are some major indentation styles which one can follow in order to write a sincere and beautiful code . The main difference between indent styles listed above lies in the placement of braces of the compound statement that often follows a control statement. There are also some other indentation styles which are not mentioned above like linux kernel form, Berkley software distribution kernel form which are something more specific and used in the source tree of the respective organizations. You can even end up creating your own indentation style, the only criteria being that it does not look horrible and follow a definite pattern or certain points which makes the whole indentation symmetric and easy-to-recognize stuff 😛 .

Remember after every opening brace, when the next line starts, please get it into your reflexes that you enter the tab button of keyboard and not indent it using spaces. Although this war between tabs and spaces goes on, I am one of the soldiers of the “tab” army, because its really a good practice.

Naming Components and Modules

As the subtopic says, the code which you write is segmented into certain modules or functions. It also consists of variables and class or structure blocks. All these things are present in your code in order to serve a specific purpose demanded by the problem statement. The variables or function names should be such that if anyone reads the function signature or variable name , he will spontaneously be able to guess the purpose for which it has been written. Suppose if you allocate a two dimensional array at some point of time and you write a specific function, a name like alloc2D() or 2Dallocation() or mem2D() would work fine instead of writing big words such as allocatetwodimensionalarray() or writing small names such as 2D().

I do not possess any rights to change the views of any professional programmer, but I think this helps a lot, in the long run. The variables should also be named in accordance with the purpose they intend to serve. Some naming conventions represent rules or requirements which are outside the domain of the specific project or problem domain and are defined by a overwhelming set of software architecture. One example is the HUNGARIAN NOTATION. This notation is absolutely language independent and is recognized naming convention for identifiers.

Hungarian Notation is of two types :- Apps Hungarian and System Hungarian.

In this notation, a variable name starts with a group of lower case letters which are mnemonics for the type or purpose of that variable. It also follows the CamelCase where the first character of the given variable name is capitalized to separate it from those which mention the type or the type indicators. Some examples are

pX :- Denotes a pointer to type X

sz:- Denotes a null or zero terminated string

There are many other examples such as positional notation which is mainly active in mainframes and composite word schemes. In C++, keywords and standard library identifiers are mostly lowercase. C++ mostly uses underscore( _ ) as a word separator. Identifiers representing macros are written in upper case letters and underscores.

Comments and Documentation

Starting with a formal definition , “In programming, comments are self explanatory statements which are intended to imply the meaning of any block written in the source code which can help anyone to read your source code and draw inference regarding the code block or the role, it plays inside the algorithm being implemented by the source code”.

In short, writing the real objective of any code being written in a file. These lines or comments are treated as insignificant portions of the source code file and are ignored by the compiler or interpreter. There are two major ways to put documentation in a C++ file.

  • Multiline Documentation or prologue documentation which starts with /** and ends with */ . Therefore this how the multi line commented blocks or statements appear –
    /**statements
    ----------------------
    ----------------------
    */
    
  • Single line Documentation or Inline Documentation which starts with // and is used in the following manner –
    int a = 5; // the variable a is initialized with 5
    

Document-able or comment-able code blocks in C++ are –

  • Classes
  • Structures
  • Unions
  • Enums
  • Functions
  • Statements
  • Variables
  • Macros
  • Conditionals

So now, we will say hello to the world again and this time with proper comments which will make it look professional as well as formal 😛

#include
/*The name of the function is main
*It is the driver function of the code
*/

int main()   // Main function signature
{   // function body starts
cout << "Hello World. I am from theoryofprogramming.com"; /* cout is output stream object responsible for printing hello world on the display peripheral */
return 0;
// function body ends
}

So, the above code has a very bad comment, adjacent to the cout statement just because of two reasons –

  • A multiline comment in order to explain a single statement is overarching.
  • The comment is too long enough and deviates the attention unnecessarily.

Now this is something poetic and I believe every programmer is a poet. So, I leave on you to think what can be an appropriate comment for that “cout” statement 😀
The most important part and generally arises from the mind of cryptic programmers. “Nested Comments”. Well personally, I do not prefer it because I can hardly think of any circumstance where it might be needed. Nested Comments can be thought of as –

/*This is theoryofprogramming.com
//welcome readers */

Or

//This is a /*legal comment*/ from theoryofprogramming.com

Or

/*This is a legal comment /*nested comment */ from theoryofprogramming.com*/ :p

The first and second one looks absolutely good and can be treated as nested comments. But what about the third one. Imagine, if you were a compiler and you have been told to parse the third statement character by character. You would have thought in the following manner –

  • Encountered a “/*” token. My comment is going to start from this point.
  • You continue to ignore every character that you face after it.
  • As soon as you get a “*/” together , you think that this is the end of the statement.

This is exactly what happens and you end up hard coding a line “from theoryofprogramming.com*/” which the compiler treats as a piece of code and tries to compile it and congratulations you receive a compiler error!! So nested comments are confusing to use although the modern IDEs does not allow us to commit such a mistake but still nested comments are an absolute nightmare and that is why C++ forbids the use of nested comments. Obviously it eases out the parsing for the languages and I find this absolutely well as a programmer too. However, if you already got a multi line comment in a code block that you want to comment out. You can make the compilers optimize away the fact, by surrounding it with #if 0 . This is just a trick and does not need any special attention. This is how it is done.

#if 0
/*

*/
endif

In short, three words i.e indentation, documentation and variable naming . These three things are very important for a programmer to first realize their utilities and then make use of them in a sincere manner. Two important points which one should always keep in mind while using these words: brevity and clarity. Hope of you have a nice day. Enjoy and write beautiful codes. 🙂

5 thoughts on “Writing Professional Code in C++

Leave a Reply