- Green Army Robotics - http://greenarmyrobotics.org -

Coding Style for ROBOTC

Posted By greenarmy On December 23, 2011 @ 2:27 pm In ROBOTC | Comments Disabled

Although the aesthetics of a FTC student’s code may be the least of their concerns while they are struggling to hack something together to drive their team’s robot in a straight-line, the readability of the code is crucial to writing high-quality & bug free software.  In this article we’ll take a look at some simple coding style concepts and rules which FTC programmers can use to make their code cleaner & more professional.

  1. Why bother with style?
  2. Traditional C coding style guides
  3. File layout
  4. Whitespace
  5. Naming
  6. Forum code tags

Why bother with style?

Professional software developers have understood from the beginning  that good code is more than successfully compiling or functional correctness.  Good code is human readable.  It is easy to understand and easy to change.

This is as important in an FTC competition as it is for a website, a desktop application, or a Fortune 500 company’s n-tier software system.  You will want to add features or new capabilities to your tele-op code.  You will want to tweak your autonomous routines.  Chances are that you will want to explain your code to another student on your team who will either work with you or take over for you once you graduate.  Most of us will share our code with a non-team member as either an example for them or to get help from them.  In all of these cases, the readability of your code is key.
It also doesn’t hurt to create good habits now if you are even remotely interested in pursuing a degree or career related to programming!

Traditional C coding style guides

ROBOTC is based on good old ANSI C.  It is not however ‘C’.  A lot of the existing literature for C style and coding standards may not be completely applicable to ROBOTC, but the majority of the guidelines and their rationale is.  Here we will not cover style rules in depth for every aspect of the ROBOTC language as that would make for an extremely long article, but it is likely worth your time to reference some existing style guides for C to help flush out areas not covered here.

Below are a few examples I found with a quick Google search:

File Layout

There are several sections of a typical ROBOTC file which we will look at here.

Pragmas for motor and sensor setup
Any header comments (Optional)
* Although most traditional header comments are the first thing in a C file, ROBOTC requires the pragmas to be the first thing in a file.
#includes (JoystickDriver.c, any 3rd party drivers, customer header files, etc.)
You should define these in an order of the most base/common first, particularly if one include references another.
#define statements (defined variables & macros) (Optional)
Typedefs & structures (Optional depending whether you’ve defined any custom datatypes)
Function prototypes (Optional)
A function prototype is a declaration of the function’s signature (it’s return type, name, & arguments), but without a body.  It is used by the compiler when it needs to resolve references to functions not yet compiled as it works it’s way through the code.  An example where you may need to define a prototype is when you have code which calls a function defined lower down in the file.  You can usually avoid this by defining functions above the code which calls them.
Global variables (variables declared outside of a function or task which can be accessed anywhere in your file)
Functions & tasks
* Task Main is usually the last one as it should ultimately reference all other functions & tasks, but none of them should reference it.

Whitespace

Correctly using whitespace is key to readable code.  Extra whitespace makes absolutely not difference to the compiler & is actually dropped at compile time.  It is only there as a visual aide to the programmer & should be used as much as possible to communicate the meaning of the code to a human reader.

Take a look at the code examples below.  They are all equivalent.  The only difference is the use of whitespace within the ROBOTC syntax.

//example 1
if(joy1Btn(1))motor[sweeperMotor]=50;else motor[sweeperMotor]=0;

//example 2
if(joy1Btn(1))
  motor[sweeperMotor] = 50;
else
  motor[sweeperMotor] = 0;

//example 3
if(joy1Btn(1)) {
  motor[sweeperMotor] = 50;
} else {
  motor[sweeperMotor] = 0;
}

//example 4
if(joy1Btn(1))
{
  motor[sweeperMotor] = 50;
}
else
{
  motor[sweeperMotor] = 0;
}

The 4th example is likely the easiest to read,  however it also consumes the most space on the screen.  One nice advantage of the 4th example over the 3rd is that it extremely easy to see where the opening and closing braces line up.  This is a common source of trouble for new programmers and adopting a convention where all braces are on their own line can make any missing or mis-matched brackets trivially easy to catch rather than having to play the game of manually searching for matching pairs when you have one too many or one too few.

This advantage is more obvious once you have nested conditions.  In the fictitious example below, we have the style from example 4 on the left and from example 3 on the right.  You can see the same bracket pair highlighted in each.  Which is easier to read?  Which is easier to debug?  Hint: there is no universal right answer.

Blank Lines

Use blank lines to visually separate out groups of related statements much like you would use paragraphs when writing prose.  In the main loop of your task main, you may put blank lines between the call to getJoysticketSettings() and the drive code.  Inside the drive code, you may put blank lines between the code which controls the drive motors and the code which operates an arm.  The point is to visually separate out the logical groupings of statements to make it easier to read.

Spacing

Within a statement you should add spaces between operators and arguments for clarity.  Compare the two examples below:

inRange = SensorValue(sensor) > getDistance(target, mode) + OFFSET;

inRange=SensorValue(sensor)>getDistance(target,mode)+OFFSET;

The second statement is unnecessarily squished together and harder for a reader’s eyes to parse.  Use spaces around operators and between arguments.  Colored syntax highlighting in the IDE helps, but don’t rely on it alone.

Indentation

You should have noticed by now that all the code examples up to this point indent each line further in as the statements nest deeper.  This guideline is pretty straightforward and makes one of the largest difference.
Consider the previous example with our exampleFunction().  Below is the same function written with and without proper indentation:

The code on the right-hand side could make even a robot cringe.  If you find your code looking like this, don’t worry because the ROBOTC IDE has a handy built-in function to automate the indentation.
From the menu, select Edit, Code Formatting, Format Whole File.

There is even a shortcut for this utility (Ctrl+Shift+Alt+F) plus an icon on the menu bar which looks like a magic wand:

If you take nothing else from this article, I hope you remember this utility.

You’ll notice that there are two additional format options related to tabs.  This is there for folks who prefer to indent using tabs rather than individual spaces.  By default, the format command will use individual spaces, but you can convert those spaces to tabs or tabs to spaces.
Tabify Whole File ==> Automatically converts all blank spaces used for indentation to tabs (does not set indentation for you)
Untabify Whole File ==> Automatically converts all tabs used for indentation to blank spaces (does not set indentation for you)
Format Whole File ==> Automatically inserts/removes blank spaces to correctly set the indentation for you.

Naming

A lot of coding style rules have appeared over the years around naming standards.  Here we’ll cover just a few of the ones which are easily applicable to FTC programmers.

  1. Use Meaningful Names
    If you have a variable for the distance traveled consider naming it something obvious like “distanceTraveled”.  Names like “dist” or “dstTvl” are ambiguous and unclear.  Although there is limited space on the NXT, naming your variables poorly is a poor method of optimizing space in compiled code.  Use good names.
  2. Use Headless Camel Case for Variable and Function Names
    Camel Case is the proper name for the convention of capitalizing only the first letter of each word in a concatenated name.  Headless camel case refers to starting the name with a lower-case letter and then only capitalizing the first letter of subsequent words in the compound.  ex:  ”thisIsAHeadlessCamelCaseExample” 

    1. Global variables should be capitalized (use regular camel case).
      If you have a global variable (one defined outside of a function or task), you should name it beginning with a capital letter.  ex:  ”ThisIsAGlobalVariable”
  3. CONSTANTS should be named in all caps with underscores (_) used to separate out words/elements in the name.
    There are two methods of declaring a constant in ROBOTC.  One is with the #define statement, the other is to use the ‘const’ attribute.  For example: 

    #define MAX_RANGE 25;
    const int MIN_RANGE = 10;

    1. Enum values should also be considered constants and named in all caps.
  4. Booleans should be named with a helper verb such as “is”, “has”, etc. which helps illustrate what the positive state of the boolean represents/indicates.  Adding in a verb allows you to mentally ask the bookean a question that its true/false state can answer.  If you have a boolean flag to indicate that your robot has reached a position, poor name choices would include “position”, “posFlag”, or “positionNotReached”.  A better name choices might be “isPositionReached”.  A reader can instantly understand what a true/false value in the variable means:  is the position reached?

Forum Code Tags

If you’re using ROBOTC and haven’t visited the official ROBOTC forums you’re missing out on a lot of great information and experience.  One of the most common mistakes a new poster makes is to post a code sample in the forum like regular text.  This is bad because the forum will trim out all the beautiful whitespace we worked so hard to use up above.  The simple fix is to use the code tags in the forum post screen which are there specifically to preserve formatting such as blank lines and indentations.

Select your code in the text box and then click the Code tag button.  This will wrap your selected text in [code] [/code] tags and preserve the formatting of your code in the forum display.


Article printed from Green Army Robotics: http://greenarmyrobotics.org

URL to article: http://greenarmyrobotics.org/robotc/coding-style-for-robotc

Copyright © 2011 Green Army Robotics. All rights reserved.