Writing code can sometimes be the most difficult part of any project. If you don’t organize everything from the start – especially for big projects — the coding processes and code management afterwards may end up not just time consuming, but also a big headache.

Good code is maintainable, reusable, and testable. The following tips address how you can approach different coding tasks and how to keep everything as neat as possible.

In the following examples, Python is used as programming language.

Page content

Plan your coding

When starting up a big project or an advanced function, having a pre-made plan will often save you a lot of time. Even though everything seems clear at first, you may have forgotten or will forget something crucial while writing.

A good plan should contain information about your coding approach, when the different variables are known and unknown, and what the output of each code block is supposed to be. Knowing all this information in advance will help you locate difficult sections of your code, as well as prevent unnecessary code and rewriting.

Understand your code

When writing code, some methods are regarded as better then others, while some are also clearly faster and shorter than others. Being aware of such methods is a great advantage, but if you don't feel comfortable writing them, either because you don't understand them well enough, or they don't match the format of the rest of your code, don't do it. More than anything else, you have to be able to interpret and explain what you have written, both to yourself and others. Writing faster and more advanced code is a skill you will develop over time, but it requires you to master the basics first, so don't rush into it.

An example of this is shown below where both methods does the same. The only difference is the amount of lines and difficulty of the code.

Example: Different methods and difficulty, same result
# Problem: We want to switch the two variables, "a" and "b", with eachother

a = "a"
b = "b"

# First method:
# This is the easiest and most inuitive method
# It uses a third variable "temp" to switch the variables
temp = a
a = b
b = temp

print("a = ", a)
print("b = ", b)


# Second method:
# This is the slightly more advanced method (available in Python)
a, b = b, a

print("a = ", a)
print("b = ", b)


# Output of both methods:
a = b
b = a
# As we can see, both methods does exactly the same, and if you were to choose one, don't just pick the one that looks the fanciest,
# make sure you understand it.

Write useful comments

Commenting while writing will always help you out in the long run. Your code may seem very simple and self explanatory at the time of writing, but to someone else, or yourself in a week, it is not necessarily that simple. Write meaningful, single line comments for vague lines, and more detailed descriptions for more difficult sections. Also, remember to keep updating your comments when updating your code.

Test your code

Your code should be tested continuously. After writing a new function, take a minute to test it before you insert it into the rest of your code. This will help you locate both trivial and more complex mistakes much faster.

When testing, always try some different parameters to evoke a mistake. Remember, finding a mistake when testing is not a bad thing, it is simply a great opportunity to make your code better. Below is an example of a trivial mistake that can easily be located if tested a bit. Do you spot it?

def f(x):
    return x - x**3/5 + 98/x**2
Solution
# Calling our function f(x) with x = 0 results in a division by 0, which is not allowed. 
# This is easily detected when testing our function while looking for possible errors.
# Below is a simple fix to our problem

def f(x):
    if x == 0:
        print('You can not divide by 0, try again with another value')
        exit()
    return x - x**3/5 + 98/x**2


Debugging

Using a debugger

Most editors have an embedded debugger. Getting used to the debugger may seem hard and useless at first, but once you get comfortable with it, it will do you wonders. The debugger allows you to go through your code step by step while keeping track of all variables at all time. This makes it very easy to narrow down errors to single lines or variables, thus easier to fix.

Using the internet

When getting an error, you can be almost 100% sure that someone else has gotten the same error as you before. Very often, it has also been made a thread somewhere explaining how to fix it. By simply copy-pasting the error into a Google search and pressing enter, you will have a good chance of locating an article or comment dedicated your error. Sometimes you might have to include or remove something in your search to make it better, but this is something that comes with experience.

When doing so, you will find a lot of explanations that may seem too advanced at first, but don't let this scare you away. Take a moment to read through the text, try to interpret what they did, and see if it is something you can try out yourself. This is because such articles/comments often include an explanation of the error at a deeper level, where as we often only need to know how to fix it.

The search-process described above is a skill, and is not something you will master at first, but will learn over time. We highly recommend you to do this when you encounter problems, as it is a very rewarding skill to possess, not only when coding.

Use meaningful names

The name of a variable, class or function should in itself explain what it does and why it's there. If a name requires a comment, it does not reveal it's content. Take a look at the example below, which variable is easiest to interpret?

int d = 3600	# Seconds in one hour
# vs
int secInHour = 3600

Beware of names with very few differences, making them difficult to seperate.

int likesAtMDGFacebookPage
# vs
int likesAtMGPFacebookPage

Use pronounceable names.

str famBlvd
# vs
str famousBoulevard

Naming conventions

When writing code, there are many different naming conventions in use. When seperating words within a single name, the two types most used are the underscore-method and camelCase-method.

int this_is_the_underscore_method
# vs
int thisIsTheCamelCaseMethod

Unless you are told to use one specific method, choose the one you prefer the most and stick with it. Mixing the two methods is a recipe for disaster, and should always be avoided.

Use some extra space when necessary

Writing readable code is essential when coding, and using spaces within your code is an easy way to improve the readability by a lot. Take a look at the short code example below, and see what a couple of extra spaces does to the code.

>>> from sympy import *

>>> x=Symbol('x')
>>> solve([x+5*y-2,-3*x+6*y-15],[x,y])
{x: -3, y: 1}
# vs
>>> x = Symbol('x')
>>> solve([x + 5*y - 2, -3*x + 6*y - 15], [x, y])
{x: -3, y: 1}

The use of whitespaces in your code does not affect the performance of your code. Some editors will help autoformat your code while writing. This is a great feature, so check if your preffered editor has this possiblity.

Data visualization

Visualizing your data is a great tool, and just a few changes to your plots or images may make a huge difference when finally presented. To read all our tips and tricks for visualizing data, visit Data visualizing using Python.

Some coding quotes to keep in mind

“Clean code always looks like it was written by someone who cares."

 – Robert C. Martin


“The ratio of time spent reading (code) versus writing is well over 10 to 1 ... (therefore) making it easy to read makes it easier to write.”

 – Robert C. Martin


"The first rule of functions is that they should be small."

 – Robert C. Martin


“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”

 – Martin Fowler


“First, solve the problem. Then, write the code.”

– John Johnson

  • No labels