Commentary on science, math, education, and aerospace.
Rate this Entry

# Posting Source Code in Computing and Technology

Posted Jan12-12 at 07:16 PM by jhae2.718
Updated Feb1-12 at 08:04 PM by jhae2.718

When posting code on Physics Forum for help, it's important to make sure it is readable and understandable. Directly pasting code into a post fails to accomplish this, as all formatting and whitespace is stripped by the forum software. Indentation and formatting exists for a reason: to allow others to easily read and comprehend your code. This is especially important in languages where whitespace is significant, such as the Python programming language.

The following is an example (using Python) of how not to post code:

def getLastPost():
f = open(CONFIG_FILE, 'r')
for line in f:
if 'lastArticle=' in line:
lastArticle = line[12:]
f.close()
return int(lastArticle.rstrip())
f.close()
return RETURN_PARSE_ERROR

All structure is lost, and it is not clear which statements are included in the if block. This has the effect of making it extremely difficult to follow the logic of the code. Remember, those of us answering questions are doing it on our free time and without compensation, and we're less likely to read through pages of unformatted spaghetti code. The best way to get a response is to put effort and thought into your post. (This goes for all the Homework Help sections as well.)

How then, should code be posted to make it readable? The answer is BBCode code tags:

Code:

# Code goes here.
You can type these in manually, or use the button provided in the advance editing interface:

Here's the same code posted in code tags:
Code:
def getLastPost():
f = open(CONFIG_FILE, 'r')
for line in f:
if 'lastArticle=' in line:
lastArticle = line[12:]
f.close()
return int(lastArticle.rstrip())
f.close()
return RETURN_PARSE_ERROR
As you can see, the code is correctly formatted and is much easier to follow and understand. An added benefit is that the code can be directly copied and pasted into an editor preserving structure.

To go the extra mile, you can use the color tool () in the advanced editing interface to do syntax highlighting:
Code:
def getLastPost():
f = open(CONFIG_FILE, 'r')
for line in f:
if 'lastArticle=' in line:
lastArticle = line[12:]
f.close()
return int(lastArticle.rstrip())
f.close()
return RETURN_PARSE_ERROR
There's also a wonderful Python library called Pygments that can produce BBCode for syntax highlighting for a variety of languages.

Finally, don't forget to explain what the inputs are, what the outputs should be, and what errors are occurring. Commenting your code is also a great help, so we can grok the code faster.
Posted in Uncategorized