Writing Code in a Professional Manner

INTRODUCTORY PROGRAMMING CLASS DISCUSSION BOARD ARTICLE

“Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. Code for readability.” – John F. Woods

In order to have your code respected and appreciated, it need not only to be efficiently programmed and well constructed but also well written and well formatted! Yes, not having bugs is essential and of primary importance; however, what good would it be if it can only be poorly understood, barely maintained, or hardly developed?! A professional programmer always keep the code clean, formatted, and well commented.

… Though one may question these factors as how their style is made or picked. Well, there are conventions and defined styles for almost everything: variable and function naming, indentation, and even commenting. When programmers worked on large projects, they’ve noticed that abiding a convention or a standardized style always ease up the development process and understandability of code written by different coders.


1. Naming

The most important rule when it comes to variable and function naming is consistency. A programmer should pick a naming and casing style and adhere to it through out the code. Here are some of the most common casing styles:

  • All caps: EXAMPLEVAR
  • Sentence case: Examplevar
  • Camel case: ExampleCase
  • Camel back: exampleCase
  • Lower case: examplevar

The point of using specific casing is to have unity in the written code, and also to allow the reader/maintainer to quickly acknowledge the type of variable he’s reading.  Different types of variables should have different types of casing. Typically, preprocessor definitions and constants are capitalized, and functions and variables are of two different styles – say camel back and lower case, respectively. Of course, you and any other reader would deem all caps, sentence case, and lacking from a readability point of view – and I absolutely agree. Normally, they would have each two words separated with an underscore. Thus, having the refined casing style:

  • All caps: EXAMPLE_VAR
  • Sentence case: Example_var
  • Lower case: example_var

The usage of other symbols is debatable because they’re often used to indicate a specific meaning. For example, starting with underscore _variable indicates the variable is a detailed implementation variable, temporary, or a private variable. It could easily cause confusion if underscores were to be used arbitrarily.

Although I have not mentioned that naming should be meaningful and relating to the purpose of the variable and function, it is very important to have clear self-descriptive naming. As an example to demonstrate how this all fits together, I will first introduce a badly cased and styled C code then followed by an improved version.

#define max 80

void rep(char c, int r)
    {
    int i;

    if (r>max)
        r=max;

    for (i=0; i<r; i++)
        printf("%c", c);
    }

The function has to be traced in order to have its functionality understood. That’s not good. Now notice how different casing styles for definitions, variable, and function naming will be used, also how the names are clear and self-descriptive.

#define MAX_REPETITION 80

void char_repetition(char _char, int repetitions)

    {
    int iteration; //or i, i is widely used and common

    if (repetitions>MAX_REPETITION)
        repetitions=MAX_REPETITION;

    for (iteration=0; iteration<repetitions; iteration++)
        printf("%c", _char);
    }

2. Indentation

Indentation, possibly the most argued writing style. Spaces ‘ ‘ or tabs ‘\t’? Single-line function headers or multi-line? Should the the first curly bracket be on the same header line or on a new line? Should it be indented? Well, basically, it’s a matter of preference as different people feel more relaxed to different indentation styles. However, for professionalism and formality purposes, the style must be unified for all source codes and files. You would never have to follow a certain style unless you’re working on a group project, and it is very important to comply with the convention. There are a lot of different indentation styles originating from different teams through history. Some are more common than others, and some are weirder than others. But one thing for sure is that you must use a certain single style for an entire project. Here are some of the most recognizable:

  • Kernel style by Linus Torvalds – used in kernel source codes: single line header, brackets on separate lines and unindented, indented blocks, single-line conditional brackets.
int foo(int bar, int baz)
{
    if (bar < 0) {
        baz = 0;
    } else {
        for (bar = 1; bar<baz; bar--)
            baz = 0;
 
    }
return baz;
}
  • Allman style – the ISO C style: single-line header, brackets on separate lines and unindented, indented blocks, multi-line conditional brackets.
int foo(int bar, int baz)
{
    if (bar < 0)
    {
        baz = 0;
    }
    else
    {
        for (bar = 1; bar<baz; bar--)
            baz = 0;
    }
    return baz;
}
  • GNU style: multi-line header, brackets on separate lines and unindented, indented blocks, multi-line conditional brackets.
int
foo(int bar, int baz)
{
    if (bar < 0)
        {
            baz = 0;
        }
    else
        {
            for (bar = 1; bar<baz; bar--)
                baz = 0;
        }
    return baz;
}
  • Whitesmiths style: single-line header, brackets on separate lines and indented, multi-line conditional brackets and indented.
int foo(int bar, int baz)
    {
    if (bar < 0)
        {
        baz = 0;
        }
    else
        {
        for (bar = 1; bar<baz; bar--)
            baz = 0;
        }
    return baz;
    }


Now this is important because it defines the readability for code. Indentation styles are not strictly for C code as exemplified, it could be used for any other language. The point of it is to have a unified well established style so that all source codes of a project look the same causing it to be easily readable and understandable. Also, it is necessary that a single indent is defined whether it’s 2, 3, 4, 8 spaces, or a tab character and used as defined through out a project.

3. Commenting

Commenting code is essential for debugging and maintenance. It is also known as documenting – to have your code documented. I have yet to come across standards for commenting; however, there are some practices that are very useful.

One practice is to have a header comment: large block of comment in the beginning of a source code file to explain the file, authorship, or license. Here’s an example of a header comment of a source code file written for an old project:

/*
    System Programming Lab (CS222) Project

    Name: Mohammed A. Mustafa
    ID #: 209115739
    Mail: 209115739@sci.kuniv.edu.kw
    
    File: Argument handler - parsing and displaying functions for main()
    DATE: Dec, 10-11, 2012

    Compatibility: All systems* (check notes)
    
    About:         
        This file contains a set of functions that are used by the main() 
        function of the program. They are built with the main.c file as a basis
        for variables, thus, this cannot be used as a library.        
*/

Another practice which is very professional and dependable but consumes a lot of time is to have a documentation for every function, explaining name, function, pre, post, and side effects. Here’s an example of old SML function (focus on the commenting style and not the language):

(*	isPrime(n:int)
	TYPE: int * int -> bool
	PRE: none
	POST: true if n is prime, false otherwise
	SIDE EFFECTS: none
	
	EXAMPLE: isPrime(42);
	OUTPUT: val it = false : bool
	
	NOTE: This function is a proxy/wrapper function for isPrime_()
*)

fun isPrime(n:int) = isPrime_(n, n-1)

And of course, the practice we have always been doing: to have regular comments describing functions and parts of codes that are a bit complex and require explanation. But never should you ever not document your code if you wish to have your code respected and appreciated.

Conclusion

You may have noticed that I did not mention any programming related points: programming practices, program structure, or division of program into constructive libraries. These may seem more important than code styling; however, it could be debated because even if a program is written efficiently and out of bugs, it may not be readable or maintainable. When it comes to professional programming, this level of code clarity is expected. I know it may seem a hassle to do all of this, but as of experience, it only becomes easier and more beneficial the more you practice it.

Don’t be selfish, few extra keystrokes could save you a headache, 3 hours of debugging and shouting, and probably 7 cups of coffee!

Advertisements

~ by AnxiousNut on February 5, 2015.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: