Some Rules I Follow to Write Cleaner Code

5 minute read

Intro

It’s been a while since I wrote a post. There’s a lot going on, and I finally (kinda) picked myself up after the few last hellish months. I got this post idea all of a sudden today, thinking about applying for a CS TA position next year. These are some rules I follow to write cleaner code. They are not like official or universal rules, but just my code styles. The code segments below are in Python, my favorite programming language. But the rules are not limited to Python’s code styles.

Let’s get started!

1. Start a Boolean variable’s name with a positive verb

I think this one is pretty much universal and is the recommended way to name a variable. A Boolean is a variable whose value is either True or False (capitalized because the code in this post is in Python). Since it indicates a state, I always start a Boolean variable’s name with a verb. Let’s look at an example:

# has_char indicates if there's at least one character in a list
has_char = False # Initialize it to False
for item in ["a", 1, 2, 3]:
    if type(item) is str: # If there's at least one str,
        has_char = True # We just update has_char to True
print(has_char)

In the example above, if there’s no string in the list at all, has_char will never be updated to True. This is because we only update has_char to True only if there’s at least one item whose type is str (String). In this particular example, we will print True as a result.

Let’s look at another code segment where the Boolean variable has_char is just named char.

# char indicates if there's at least one character in a list
char = False # Initialize it to False
for item in ["a", 1, 2, 3]:
    if type(item) is str: # If there's at least one str,
        char = True # We just update char to True
print(char)

It’s the same code, but the only difference is the Boolean variable’s name (has_char vs char). But if you think about it, since we want to show some state (whether there’s at least one character in a list), it’s better to use has_char instead of just char.

And we have one more example to compare:

# char indicates if there's no character in a list at all
does_not_have_char = True # Initialize it to True
for item in ["a", 1, 2, 3]:
    if type(item) is str: # If there's at least one str,
        does_not_have_char = False # We just update does_not_have_char to False
print(does_not_have_char)

This code is different in that we’re checking whether there’s no character in a list at all. In the previous cases, we checked if there’s at least one character. Here, we’re updating does_not_have_char to False if there’s at least one item of type str. Now, let’s look at all the three examples. Which do you think is the most clear example where we can immediately tell the Boolean variable is Boolean?

I believe it’s the first and third ones because they start with a verb. However, the third one that has does_not_have_char is a bit confusing. Instead of checking if there’s no character at all, why don’t we just check if we have at least one str variable, and just report the result?

In short, it’s always better to name a Boolean variable starting with a verb, such as “is” or “has.” Be sure to use the singular form here. Additionally, it’s more readable if you name the Boolean variable positive. In other words, don’t make a Boolean like does_not_have_char and set it to True. Instead, we can just check has_char which makes the code easier to read.

2. Start a function’s name with a verb

What is a function? It’s code that we can execute repeatedly providing the necessary arguments (if there’s any). Let’s first look at examples.

def get_largest(int_list):
    return max(int_list)

Note that the max function returns the largest item in an iterable or the largest of two or more arguments. Compare the code above to this:

def largest(int_list):
    return max(int_list)

When we call the functions respectively, we’ll write get_largest(some_list) and largest(some_list) (some_list is just an example list of integers). Just look at how we call each function. Remember, a function is a thing that does some work, whether it calculates some stuff, returns the largest item in a list, etc. We can easily tell get_largest a function because the name itself implies that the function gets the largest item.

3. If True, else False

This is what I always prefer.

if has_char:
    print("This list has at least one char!")
else:
    print("There's no char.")

When has_char is True, we print the first message and otherwise, we print the second one. But what if we reverse the order?

if not has_char:
    print("There's no char.")
else:
    print("This list has at least one char!")

This is still pretty easy to read but it’s just because the code is short and simple. In my opinion, it’s better not to check False first and then go to else or elif (“else if” in Python).

4. Use a list (or an array) when there are a lot of parameters

Examples before explanation.

def add_numbers(first, second, third, fourth, fifth, sixth, seventh):
    print(first + second + third + fourth + fifth + sixth + seventh)

This function has a very long signature because there are 7 parameters. When we call this, we’ll write something like this:

add_numbers(4, 2, 4, 6, 7, 2, 4)

We don’t want this because it doesn’t look very good. Instead, we can just pass an array of those arguments!

def add_numbers(num_list):
    print(sum(num_list))
    
add_numbers([4, 2, 4, 6, 7, 2, 4])

The sum evaluates an iterable from left to right and returns the total. The function add_numbers looks simpler here because we don’t have many parameters. Generally, I prefer to pass an item or an array when there are more than 3 parameters.

Outro

Thanks for reading, and I’ll try to be more active on my blog!

Leave a comment