Clean Coding for Non-Coders
Image credit: https://creativecommons.org/publicdomain/zero/1.0/

Clean Coding for Non-Coders

Software development is encroaching into many different disciplines. Scientists, engineers, marketers, and many other professionals write software more often than in the past. Many of these individuals learn to program, but sometimes struggle to write clean code.

Cleaner code is easier to debug, extend (add new features), and maintain. Here are a few tips to keep your code clean and easy to read.

Note: most of these examples are written in Python. If you are not familiar with basic Python syntax, I suggest reviewing it first.

1. Use Meaningful Names:

  • Choose descriptive and meaningful names for variables, functions, and classes.

# Bad example. "l" could mean anything.

l = [14, 16, 12, 16]        
# Good example. The name of the list describes what's inside.

ages = [14, 16, 12, 16]        

  • Describe functions with their return values (if they have one). If a function returns true/false, name it with a yes/no question.

# Bad example. The function name doesn't describe the return value.

def growHair():
    if age < 60:
        hairLength += 1
    return hairLength        
# Good example. The function name asks a yes/no question.

def isAgeOver65(age):
    return age > 65        

2. Have Consistent Formatting:

  • Stick to a coding style throughout your project. If available, use a tool that can auto-format your code, such as ClangFormat.

Note: these examples are in C because Python enforces some formatting rules

// Bad example. These functions have different formatting.

void takeBath() {          // Note the '{' is NOT on a separate line
    turnOnHotWater();      // Note the indentation
}

void takeShower()
{                          // Note the '{' is on a separate line
turnOnHotWater();          // Note this line is not indented
}        
// Bad Example. Different naming styles are used.

// This function uses camelCase style
void takeBath() {
    turnOnHotWater();
}

// This function uses snake_case style
void take_shower() {
    turn_on_hot_water();
}        
// Good example. The formatting and styles are consistent.

void takeBath() {
    turnOnHotWater();
}
void takeShower() {
    turnOnHotWater();
}        

3. Comment and Document Your Code:

  • Your code should, for the most part, be self-documenting, i.e., you shouldn't need a comment to tell the reader what the code does. Instead, comments should explain why the code does what it does.

# Bad example. The comment is redundant.

# returns true if the name ends with 'son'
def doesNameEndWithSon(name):
    if name.endsWith('son'):
        return True
    return False        
# Good example. The comment explains why the code works.

def isNameSwedish(name):
    # in our dataset, all Swedish names end with 'son'
    if name.endsWith('son'):
        return True
    return False        

  • Document a summary of what your code does. This can be done in a text file or a diagram

# Here's some example code to document

peel()
while(not bananaIsFinished()):
    bite()
    chew()
    swallow()
discardPeel()        
# Here's the example documentation for the above code

Simple procedure for eating a banana        

4. Simplify

  • Less is more. It's easier to read code with less branches, loops, etc.

# Bad example. These loops can easily be combined.

def replaceMultiplesOf2(word):
    for i in range(word.length()):
        if word[i] == '2':
            word[i] = ' '
        if word[i] == '4':
            word[i] = ' '
    for i in range(word.length()):
        if word[i] == '6':
            word[i] = ' '
        if word[i] == '8':
            word[i] = ' '        
# Bad example. We have 1 loop, but there are 4 'if' statements.

def replaceMultiplesOf2(word):
    for i in range(word.length()):
        if word[i] == '2':
            word[i] = ' '
        if word[i] == '4':
            word[i] = ' '
        if word[i] == '6':
            word[i] = ' '
        if word[i] == '8':
            word[i] = ' '        
# Good example. We only have 1 loop and 1 'if' statement.
# Note that this code does the same thing as the examples above.

def replaceMultiplesOf2(word):
    numbers = ['2', '4', '6', '8']
    for i in range(word.length()):
        if word[i] in numbers:
            word[i] = ' '        

5. Avoid Repetition:

  • Don’t repeat yourself. Use functions, loops, and abstractions to eliminate duplicate code.

# Bad example. Here we have lots of unneeded duplication.

def eatBanana():
    takeBite()
    takeBite()
    takeBite()
    takeBite()
    takeBite()
    throwAwayPeel()        
# Good example. We don't have any duplication.

def eatBanana():
    for i in range(5):
        takeBite()
    throwAwayPeel()        

6. Use Version Control:

  • When modifying code, use a version control tool (e.g., Git) to track code changes. Compare the old code (red) to the new code (green)

Article content
After changing the code, use the "diff" to see what changed

7. Test Your Code

  • Test your code to ensure it works correctly. Write test code if possible.

# Here is the code we want to test.

def isMultipleOf3(number):
    if number < 3:
        return False
    else
        return number % 3 == 0        
# Here is a simple test.

def testIsMultipleOf3():
    assert isMultipleOf3(3)
    assert isMultipleOf3(27)
    assert not isMultipleOf3(0)
    assert not isMultipleOf3(49)        

To view or add a comment, sign in

Others also viewed

Explore content categories