Brackets, Semicolons, or Nothing, Oh My

CarbonNYC on Flickr

If you are ever in a room full of programmers and want to have fun, ask what indentation style works best in coding. You’ll get a lively debate, at best. Furniture will be thrown at worst. You see, there is no right answer. And every language has its own quirks people grow to love or hate.

This Code Snippets section of the magazine explains parts of programming languages common across most or all languages. It's a great way to understand how languages work. Learning how to code also should be much easier and less frightening if I explain a part of a programming language, then show you how it works in a couple different languages.

Let's get started by talking about indentation and programming style.

What Is a Programming Style?

The quick definition: a programming style is a set of rules or guidelines used to write code. As a coder, the style helps read the code you or someone else wrote. For the programming language, the style ensures the code works when compiled or processed.

In simpler terms, a programming style uses spaces, tabs, names, punctuation, and other devices to organize code.

Here’s a great example. Imagine if you had to read this code:

if hours < 24 and minutes < 60 and seconds < 60 then return True else return False end

Now imagine this code was written in a language with this simple indentation style:

if hours < 24 and minutes < 60 and seconds < 60 then
    return True
else
    return False
end

The second example is written in the Lua language which does not require indentation. This code also works when written in Lua:

if hours < 24 and minutes < 60 and seconds < 60 then
return True
else
return False
end

As you can see, a simple style rule to break code statements into individual lines makes it easier to read code. In the first example, a single line of code with no real breaks between statements is harder to read. For a programming language, however, it might be easy to read the single line of code.

Another fun part of a programming style is naming. My favorite is CamelCase, as in a variable named PayInvoice, where the first letter of each word is capitalized and there are no spaces between words. Turns out there are two types of CamelCase: upper and lower. PayInvoice is upper CamelCase while payInvoice is lower.

What goes into a name used in a programming language can also differ. Some use a prefix like s to indicate a variable holds a string value. Naming conventions also can have length limitations, especially older languages. Programmers generally use the shortest and most descriptive names, in most cases, because it makes maintenance and reading code easier.

In the example above, you will notice there are no semi-colons, curly braces, brackets, or other characters used in some languages to mark off parts of code. The C programming language, and many languages derived from C, use curly braces to set off blocks of code. Other languages like Lua use line breaks to achieve the same result. My favorite is JSON which uses curly braces, curved braces, and angle brackets because JSON data can be nested one chunk of data inside another. Then again, JSON is a data format, not a language.

Programming style is one of the key parts to learn when you first learn a new language. Whatever the style, however, consistency helps make any code readable and easier to maintain.

What Are the Indentation Options?

There are two main ways to indent blocks of code: spaces and tabs. Because editing tools some times count tabs differently, by default as well as through settings in the editing software, spaces are considered more reliable. Python, for example, uses indentation in groups of four white spaces per indentation level instead of tabs. Unless your editing software has the ability to see tabs, it can be difficult to code or maintain code that uses tabs instead of spaces.

Programming Style for C

The programming style for the C language is both everywhere and nowhere. Here is a switch statement, for example, from one of the original style documents for the C language:

if (strcmp(reply, "yes") == EQUAL) {
	statements for yes
	...
} else if (strcmp(reply, "no") == EQUAL) {
	statements for no
	...
} else if (strcmp(reply, "maybe") == EQUAL) {
	statements for maybe
	...
} else {
	statements for none of the above
	...
}

Note the use of curly braces to mark off blocks of code, a style used in many languages like PHP and Java. The comparison statements also are common in many languages. Yet there appears to be no formal programming style document for C, only a variety of documents created over the years.

Also note the use of str in the strcmp variable. Likely str indicates the variable is a string given the possible values are strings: yes, no, and maybe.

Programming Style for Erlang

In researching this article, I was amused and intrigued to find the Erlang language uses the principle of “least astonishment” as one of its programming style. Readers of Erlang code, arguably any code, should not be surprised by what they find. The system should respond as the reader and programmer expects based on looking at code.

Here’s an example of Erlang code to show some features of their programming style:

do_something_with(File) ->
  case file:open(File, read) of,
    {ok, Stream} ->
      doit(Stream),
      file:close(Stream) % The correct solution
    Error -> Error
  end.

Several interesting things are revealed in this code. Most obvious is the use of -> to indicate the start of a task or subtask, instead of a curly brace in C or line break in Lua. Also note how file:open and file:close are indented at the same vertical level. In the Erlang documentation, including file:close within or near file:open is considered good practice. The reader expects a file will be closed if opened; closing the file in another block of code would be unexpected and harder to find.

While I cannot tell if Erlang uses spaces instead of tabs, indentation is used to mark off blocks of code and show precedence. Also note the comment uses a % to indicate the start of the comment, % The correct solution.

Programming Style for Python

As noted above, Python uses four spaces per indentation level to mark out blocks of code. Here is one example from Python’s programming style defined in PEP 8:

class Rectangle(Blob):

    def __init__(self, width, height,
                 color='black', emphasis=None, highlight=0):
        if (width == 0 and height == 0 and
                color == 'red' and emphasis == 'strong' or
                highlight > 100):
            raise ValueError("sorry, you lose")
        if width == 0 and height == 0 and (color == 'red' or
                                           emphasis is None):
            raise ValueError("I don't think so -- values are %s, %s" %
                             (width, height))
        Blob.__init__(self, width, height,
                      color, emphasis, highlight)

You can see lines 5-14 are included within the def statement on line 3. Also note how lines 4, 6-7, 10, 12, and 14 use indentation to clearly identify what belongs to the line above. This approach makes Python code highly readable, one of the key insights used to define the language.

Also note there are no semi-colons in Python, only colons (:) are used to mark off blocks of code.

Learn More

Programming Style

http://en.wikipedia.org/wiki/Programming_style
http://www.cs.rutgers.edu/~pxk/417/notes/content/Cstyle.pdf

Coding Conventions

The bottom of this article also includes links to conventions for specific languages.
http://en.wikipedia.org/wiki/Coding_conventions

Naming Conventions

http://en.wikipedia.org/wiki/Naming_convention_%28programming%29

PEP 8: Style Guide for Python Code

http://www.python.org/dev/peps/pep-0008/

Erlang Programming Style

http://www.erlang.se/doc/programming_rules.shtml

C Programming Style Guides

http://www.maultech.com/chrislott/resources/cstyle/
http://www.maultech.com/chrislott/resources/cstyle/indhill-annot.html

Visited 167 times, 1 visit(s) today