This post was originally published at Tutorial: The value of well-formatted code

Inevitably, there will be a time in your app development where you’ll need to show your code to someone else. Perhaps it’s because you’re asking for help in the forums or you’re working on a team and your teammates need to read your code. Maybe you want to sell a template to someone, or even publish your code to the Corona Code Exchange.

In all of these instances, having well-formatted code is a big aspect of how successful you’ll be as a programmer. Unfortunately, code formatting can prompt a heated argument between different programmers: do you use 3 spaces or 4 spaces per indent? Do you use tabs instead of spaces to indent? Do you put your opening curly brace ({) on the end of the line or the beginning? And so forth…

Before we look at some key areas where you can use to improve your code formatting, consider this block of code:

While the code above technically works, it’s a bit confusing to figure out what it’s actually doing. Now compare it to the following version:

As you can see, proper code formatting makes this version much easier to read and understand. The doSomething() function is clearly started and ended, variables are clearly and accurately named, they are clearly scoped within the function, and even the addToScore() function is clearly nested within its parent doSomething() function.

In the following sections, let’s look at the various code formatting issues and how you can improve your own code.

Indentation

Many developers don’t know what indentation means. Simply put, code is broken into “blocks” and blocks have a beginning and an end. For instance, when you define a function, you are creating a block of code. At some point, that block ends (in Lua, you mark the end of a block with the keyword end). Generally speaking, indentation is the intentional shifting of code within a block to the right, effectively making it more readable:

In Lua, blocks are defined using any of the following keywords:

  • function
  • if
  • while
  • for
  • repeat

All of these keywords require an end statement to go with them. The keyword (i.e. while) and its matching end should be the same distance from the left side of the editor screen. Additionally, the content inside the block should be several spaces to the right of the block’s keyword and end. For purposes of indentation, you can indent your code using either multiple spaces (3 or 4 spaces is most common) or tab indentations.

  • If you prefer spaces, you should use enough spaces so that it’s obvious the interior code is “inside” the block.
  • In the case of tabs, most editors allow you to set a single tab to represent 3 or 4 spaces, and when you backspace/delete to remove the indent, it conveniently removes the entire tab instead of forcing you to erase multiple spaces individually.

Multi-level indentation

Frequently, you will have blocks inside of other blocks, for example an if statement inside a function and a command inside of that if block. In these cases, you should indent the interior block/line one further “level” than its containing block:

A few final notes on indentation: it’s very important that you be consistent with your indentations. Don’t over-indent a block and don’t under-indent it. While proper indentation takes a little more focus and effort while you’re coding, if you fail to properly indent blocks, anybody else reading your code will struggle to understand it, and even you may become confused if you return later to inspect non-indented code blocks.

Variable names

Back in the early days of programming, for example with languages like BASIC, we only had access to variable names like A, B, I, X, Y. We used these letters in a fairly standard way — A was for arrays, X/Y for coordinates, and I for “index” (the reason many people still use i as the index iterator in for loops!).

These days, modern programming languages allow us to use far more verbose variable names, and in Lua there are a few guidelines which work well. For instance, i might be a good index variable in a very narrow scope, but it’s a horrible name for something “broader” to the overall project. Generally, the broader the scope, the more descriptive the variable name should be. Shorter names like move or player are fine for narrow-scoped variables, but the broader the scope, the longer the name should be, and frequently it should contain multiple words like playerUniformColor.

Camel case

Corona’s API calls use a system called “camel case” in which each word in a multi-word API is strung together as one longer word. There are two variants of camel case:

  1. The very first letter is capitalized and all further words are capitalized as well, for example PlayerName.
  2. The first letter is lowercase and all further words are capitalized. Corona’s APIs use this variant, for instance display.newImageRect() where new is lowercase but Image and Rect are capitalized. This variant of camel case is common among developers and it will make your code very readable for others.

Block length and nested blocks

In Lua, it’s easy to write code that can contain a lot of nested blocks. However, the longer a block gets, the harder it becomes to read and maintain. The purpose of functions is to write manageable blocks of code that will be executed over and over, and the key term here is manageable. When you have a series of function(), if, for and other blocks nested inside each other with multiple end statements associated with each, even proper indentation may not be enough to clarify the flow of logic. If an overall block of code becomes this large, you may consider pulling some of the logic out and moving it to another function.

Module length

Just like you should avoid long functions, consider avoiding long modules too. When an entire module gets too long, it becomes hard to manage. More importantly, if you are writing code near the bottom, you can’t see the things you’ve defined at the top of the module. If you are constantly scrolling up and down in your text editor to see things, the module may be unmanageable. Excessively long modules may also run up against Lua’s limit of 200 local variables, so keeping modules shorter and more concise is often good practice.

Minimizing white space

While some white space (including indentations) improves readability, excessive white space can be both problematic and pointless. Generally you should have just one space between keywords like function, if, etc. and their parameters. Compare the following two blocks:

These functions are identical in behavior, but by using a sensible amount of white space, the second version is easier to read. Spacing also helps you see where operators are (=, +, etc.). In contrast, excessive white space, particularly extra blank lines, makes your modules longer and harder to follow. Typically it’s good to use one blank line to separate nested blocks, for example before the if block above (more than one line is unnecessary).

Using a proper editor

Using a full-featured code/text editor application will greatly improve your code. These will usually manage your indentations for you. In addition, they will often provide full syntax coloring where keywords, values, and variables are colored differently to assist in readability. For example, an editor might label strings in green, and if you forget to include a string’s ending quote (“), a much larger block of code may turn green, indicating that you forgot that ending quote.

Another important feature of a proper editor is the ability to show line numbers. When Corona encounters an error in code, it reports the line number where the problem occurred (see the Debugging Guide for more information). Thus, if your editor shows you line numbers, it’s much easier to track down the issue.

While there are many editor applications available, Corona Labs endorses Sublime Text along with Corona Editor which extends the core features for specific usage with Corona SDK.

Posting code in the forums

There will almost certainly be a time when you need to seek help from other developers in the Corona forums. In most instances, you’ll need to provide some of your code for context and to clearly indicate to readers how you’re approaching the situation.

When posting code, there are several important things to remember:

1. Use the proper formatting codes

The forums support standard BBEdit tags. Unlike HTML tags, these are surrounded with square brackets ([ and ]). For blocks of code that you post in the forums, you should surround them with either [code][/code] or [lua][/lua], for example:

Alternatively, you can simply click the <> button above the content insertion field of the form:

Screen Shot 2015-06-07 at 10.49.24 PM

2. Copy and paste your code (avoid screenshots)

For other developers, it’s inconvenient to click on a screenshot of your code only to see a small screen grab, sometimes obscured in part by the Corona Simulator. Instead, please copy and paste the block of code directly from your editor into the forum submission, surrounded by the proper formatting codes discussed above.

3. Only paste enough code to discuss your problem

If you’re having a problem with a widget button, copy and paste both the function which handles the button and the code which creates the button. If other developers need more code, they will ask for it. Please do not dump an entire Composer scene into the forums — this is typically overkill and you will get much less assistance from others if you post excessive and irrelevant code.

4. Post the specific error message and line number

If you are getting an error in the Terminal/console that contains a line number, include the full and complete error message along with the relevant code. If you use the <> button as shown above, you can even specify a “starting line number” to match the exact line number in your code editor — this is an excellent way to indicate the exact line which triggered the error.

Conclusion

If you follow the practices in this tutorial, not only will you find your own code easier to read, but when you need help from other developers, more will be willing to assist you. Collectively, the techniques and tips we’ve discussed will make you a more efficient and productive developer.


From: 

This post was originally published at Tutorial: The value of well-formatted code