10 practical tips for writing code that humans can understand

Martin Fowler, software engineer, developer, author of numerous books and one of the leading experts in programming, wrote:

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." (1)

Indeed, when we talk about programming languages we sometimes forget that, for us humans, they are like a foreign language (although for nerds and geeks this isn't always the case!). We are all more or less able to study and speak it, but not all of us manage to make ourselves understood, especially when we go beyond a simple greeting or a "what's your name?" and interact in a culturally meaningful way.

Taking this quotation as our starting point, we want to talk about one of the aspects programmers most often neglect: how readable and understandable source code is to humans.

Because, just like Fowler, we believe that good software does not only need code that works without bugs (do such things exist?) and runs fast; the code must also be easy to read and understand – and therefore easy to change and maintain – even long afterwards, by the programmer who wrote it.

To put it plainly: dear developer, has it never happened to you to read a piece of code and think "who on earth wrote this mess?" before realising it was you?

The same goes for other programmers in the same team when development involves many people working on large projects who, in most cases, don't know each other and so can only rely on the code itself and its documentation.

Writing code clearly, so that it can be read and understood by many people, is therefore really very important – certainly more than people think.

An approach that, incidentally, chimes with our concept of harmony: for us at ESSE I, harmonious code is also written for others, not just for ourselves and the machine, so as to encourage smooth collaboration between team members.

In some ways, a gesture of shared human empathy.

So we want to leave you our "10 practical tips for writing code that humans can understand" and, at the end, a further reflection on this important topic.

If you are a beginner programmer or an enthusiast, unlike those who are already experienced, we think you may find them very useful.

1) Use meaningful, clear names

Our first tip is to use meaningful names for variables, functions and classes.

Names should clearly reflect their function and purpose, so avoid obscure abbreviations or overly generic terms. Well-chosen names make code easier to understand and maintain. Use camelCase, hyphens or underscores to separate words. Here are some simple examples:

Typical variable names:

customerName – Holds the customer's name.
orderTotal – Represents the order total.
numberOfItems – Indicates the number of items in a set.

Typical function names:

CalculateTotalPrice – Calculates the total price of the items.
GetUserFullName – Returns the user's full name.
ValidateEmailFormat – Checks that an email address is correctly formatted.

Typical class names:

Person – Represents a person with attributes such as name and age.
Car – Represents a four-wheeled vehicle with attributes such as make, model and year.
Student – Represents a student (derived from Person) with additional attributes such as their relationship with the school, etc.

2) Write clear, concise comments

Comment your code to explain its complex or fundamental parts. Make sure comments are clear and relevant, so they are neither superfluous nor confusing. Documentation should be a useful addition, not an obstacle.

Write them with searching the code in mind too: putting keywords in a comment can save a great deal of time during review.

Here is an example of a typical comment in Python.

# Calculate the sum of the first ten positive integers.

Remember that comments can also help IntelliSense, for example a comment above a C# method declaration listing the parameters to pass.

/// <summary>
/// Add Customer – method that adds a customer
/// </summary>
/// <param name="companyName"></param>
/// <param name="vatNumber"></param>
/// <returns></returns>

3) Look after the structure

Organise your code into blocks or sections. How? With indentation and blank lines. Use control structures such as loops and conditions to separate the parts logically. A well-organised structure makes it easier to navigate the code and quickly find the information you need.

We use Visual Studio, which takes care of indentation for us. Try pressing CTRL K+D and watch the magic!

Here is an example of code, again in Python, indented with tabs (in Python indentation is not just about making code look nice; it is fundamental: get the indentation wrong and the code will certainly behave unexpectedly).

def calculate_mean(values):
    # Calculate the mean of the input values.
    total = sum(values)
    mean = total / len(values)
    return mean

def calculate_standard_deviation(values):
    # Calculate the standard deviation of the input values.
    mean = calculate_mean(values)
    squared_deviations = [(x - mean) ** 2 for x in values]
    variance = sum(squared_deviations) / len(values)
    standard_deviation = variance ** 0.5
    return standard_deviation

# Main block of the program
data = [12, 15, 18, 10, 21, 14, 17]
mean = calculate_mean(data)
deviation = calculate_standard_deviation(data)
print("Mean:", mean)
print("Standard deviation:", deviation)

4) Add detailed documentation

Complement the project with detailed documentation for functions, methods and classes. Describe what each component does, what parameters it accepts and what it returns. Use a standard documentation style to ensure consistency.

Good documentation usually makes use of "docstrings".

What are they? Strings of text placed at the start of functions and classes that explain their purpose and use. For example, again in Python, something like this:

def calculate_mean(values):
    """
    Calculate the mean of the input values.

    Args:
        values (list): A list of numbers to calculate the mean from.

    Returns:
        float: The mean of the values.
    """
    total = sum(values)
    mean = total / len(values)
    return mean

5) Use separate modules

Don't forget to split your code into modules or classes that carry out specific functions.

This separation makes the code more manageable and understandable because it divides responsibilities among those who will work on it. Clear modules make maintenance and adding new features easier.

6) No redundancy

Avoid duplicating code by using functions or methods. This not only makes the code more efficient but also makes future changes easier.

Reusable code promotes consistency and maintainability over time. Of course, optimising code to avoid repetition takes more time and effort, but rest assured that the computer it runs on will use fewer resources, it will be more secure, and your fellow developers will thank you.

7) Test and fix

Include unit and integration tests to check that the code works correctly. Use a debugger to find and fix errors. Document the tests carried out and the results obtained.

8) Version your code

Use a version control system to keep track of code changes over time, which encourages collaboration and makes it easy to restore earlier versions when needed.

An excellent version control system is Git. Here you will find the documentation to make the most of it: https://git-scm.com

9) Format clearly

Keep formatting uniform, with a consistent style for brackets, spaces and indentation. Clear formatting makes code more readable and understandable.

Just as, when speaking a language (including your mother tongue), you have your own tone of voice, coding is somewhat the same: what matters is staying consistent with your own style and not changing it.

For example, if you usually use tabs to indent blocks, always use tabs and not spaces, or vice versa. It may seem trivial, but it is often these details that make the difference. Not only functionality but also the other team members' perception of how carefully you have programmed is important.

10) Review and improve code over time

Our last tip is this: before sharing your code with your team, review it carefully to make sure it is clear and error-free. Ask colleagues for feedback to improve the quality of what you produce. Constant review helps keep documentation up to date and useful over time.

In conclusion...

Among coders it is common to think that code commented and documented differently from how we would have done it is not good code, but that is not always so. Reading someone else's code means "entering another person's world" to understand and respect their style, always hoping it is clear.

After all, writing code is not only drawing up a list of instructions but also a creative act and an act of communication. And if, as we said, a programming language is a bit like a foreign language, it is also true that it can be learned by studying it, of course, but also by practising it, picking up the different nuances in each of our programming styles.

What do you think? We would love to hear from you with a comment on social media (for example on our LinkedIn page) or, why not, with a private message.

In any case, we hope this article has helped you make your programming more readable and fostered more understanding and harmonious collaboration between you and your fellow coders.

(1) Martin Fowler, Refactoring: Improving the Design of Existing Code, Addison-Wesley.
(Photo: Pexels)