Developing Code for Humans, Not Just Machines
DALL-E 3: A well-maintained office with a happy developer versus a chaotic office with a frustrated developer.

Developing Code for Humans, Not Just Machines

As a programmer, you may have heard the famous quote by Martin Fowler:

"Any fool can write code that a computer can understand. Good software developers write code that humans can understand."

But what does it mean to write code that humans can understand? And why is it important? In this article, I will explore the concept of code readability, which is the degree to which a piece of code can be easily understood by other developers. I will also look at some examples of bad and good code, and discuss how to improve your coding style and practices.

Why Code Readability Matters

Code readability is not just a matter of personal preference or aesthetics. It has a significant impact on the quality, maintainability, and efficiency of your code. Here are some reasons why code readability matters:

Code is read more often than it is written.

According to a study published in 2015 on IEEE, I Know What You Did Last Summer – An Investigation of How Developers Spend Their Time, when programmers are in development mode, they spend up to 70% of their time reading and understanding code. This means that the readability of your code affects not only yourself, but also your teammates, collaborators, reviewers, and future maintainers of your code. If your code is hard to read, it will take more time and effort to comprehend, debug, modify, and reuse it.

How do developers spend their time?

Code readability affects code quality.

Readable code is more likely to be correct, robust, and secure than unreadable code. This is because readable code is easier to test, review, and refactor. It also reduces the chances of introducing bugs, errors, or vulnerabilities due to misunderstanding or misusing the code. On the other hand, unreadable code is more prone to errors, bugs, and security issues, as it is harder to spot and fix them.

Code readability affects code efficiency.

Readable code is more likely to be efficient than unreadable code. This is because readable code is easier to optimize, improve, and adapt to changing requirements or environments. It also enables better collaboration and communication among software developers, as they can share and understand each other's code more easily. On the other hand, unreadable code is more likely to be inefficient, as it is harder to modify, reuse, or extend it.

Examples of Bad and Good Code

To illustrate the difference between bad and good code, let us look at some examples in Python, a popular programming language. Python is known for its readability and simplicity, as it follows the principle of "There should be one--and preferably only one--obvious way to do it." However, even in Python, there are ways to write bad and good code.

Example 1: Naming Conventions

The case sensitivity of identifier names in programming is a vital aspect of code readability and maintainability. Different programming languages and frameworks have specific case sensitivity rules and conventions, which, when followed, significantly enhance the clarity and consistency of the code. For instance, using camelCase (where the first letter is lowercase, followed by uppercase letters at the start of new words, e.g., userProfile) for variables and functions is a common practice in languages like JavaScript and Java. This contrasts with the use of snake_case (words separated by underscores, e.g., user_profile) often seen in Python.

Adhering to these conventions allows programmers to immediately recognize the type of identifier they are working with. Similarly, PascalCase (where each word starts with an uppercase letter, e.g., ShoppingCart) is typically used for classes in many languages, helping developers distinguish class names from other identifiers.

By consistently applying these case sensitivity rules, the code becomes more organized and navigable, making it easier for developers to read, understand, and collaborate effectively, especially in large and complex projects where such clarity is paramount.

Example 2: Descriptive Identifiers

Another critical aspect of code readability is choosing descriptive names for your variables, functions, classes, modules, and other elements of your code. Good names should be clear, concise, consistent, and meaningful. They should convey the purpose and functionality of the code element, and avoid ambiguity or confusion. Bad names, on the other hand, are vague, long, inconsistent, or meaningless. They make the code hard to understand and maintain.

Here is an example of bad and good naming in Python:

# Bad Naming
def f(x):
  y = x * 2
  z = y + 5
  return z        
# Good Naming
def double_and_add_five(x):
  doubled = x * 2
  result = doubled + 5
  return result        

In the bad naming example, the function name f and the variables x, y, and z are meaningless and uninformative. They do not tell us what the function does, what the parameters are, or what the return value is. We have to read the code carefully to figure out its logic and purpose.

In the good naming example, the function name double_and_add_five and the variables x, doubled, and result are clear and descriptive. They tell us exactly what the function does, what the parameters are, and what the return value is. We can easily understand the code at a glance.

Example 3: Formatting and Comments

Other important aspects of code readability are formatting and meaningful comments. Good formatting should be consistent, neat, and aligned with the conventions and standards of your programming language and community. This involves not only arranging code in a logical structure but also adding clear and helpful comments that explain complex logic or clarify the purpose of code segments. Effective comments enhance understanding without cluttering the code. Conversely, bad formatting is characterized by inconsistency, messiness, or deviation from the norms and expectations of your programming language and community. It makes the code hard to read, scan, and follow. A lack of comments or the presence of unnecessary or misleading comments can significantly hinder readability and maintainability, making it challenging for others (and often your future self) to understand and work with the code effectively.

Here is an example of bad and good formatting in Python:

# Bad Formatting
def f(x):y=x*2;z=y+5;return z        
# Good Formatting
def double_and_add_five(x):
    """
    Double the input value and add five.
    Args:
    x (int): The number to be processed.
    Returns:
    int: The result of doubling the input and adding five.
    """

    doubled = x * 2
    result = doubled + 5
    return result        

In the bad formatting example, the code is poorly indented, spaced, and commented. It does not follow the Python style guide, which recommends using four spaces for indentation, spaces around operators and commas, and docstrings for function documentation. The code is hard to read and follow, as it looks like a single block of text.

In the good formatting example, the code is properly indented, spaced, and commented. It follows the Python style guide, which makes the code more readable and consistent with other Python code. The code is easy to read and follow, as it has clear structure and separation of logic.

How to Improve Your Code Readability

Now that we have seen some examples of bad and good code, how can we improve our code readability? Here are some general tips and best practices that you can apply to any programming language:

  • Use meaningful and consistent names. Choose names that reflect the purpose and functionality of your code elements, and use them consistently throughout your code. Avoid names that are too short, too long, or too similar to other names. Use naming conventions that are appropriate for your programming language and community.
  • Use proper formatting and indentation. Format and indent your code according to the standards and conventions of your programming language and community. Use spaces, tabs, line breaks, and comments to make your code neat and organized. Use tools such as code formatters, linters, or editors to help you with formatting and indentation.
  • Use comments and documentation. Comment and document your code to explain the logic, assumptions, and decisions behind your code. Use comments and documentation to supplement, not replace, your code. Use the appropriate style and format for your comments and documentation, such as docstrings, comments, or markdown files.
  • Use modular and reusable code. Break down your code into smaller, simpler, and independent units, such as functions, classes, or modules. Use these units to compose your larger and more complex code. Make your code reusable by avoiding hard-coding, using parameters, and following the principle of "Don't Repeat Yourself" (DRY).
  • Use clear and simple logic. Write code that is easy to understand and follow, both for yourself and others. Avoid using complex, obscure, or unnecessary logic, such as nested loops, multiple conditions, or bitwise operations. Use descriptive and expressive logic, such as if-else statements, for loops, or list comprehensions.
  • Use appropriate data structures and algorithms. Choose data structures and algorithms that suit your problem and data, and that are efficient and effective. Avoid using data structures and algorithms that are inappropriate, inefficient, or ineffective, such as arrays, linked lists, or bubble sort. Use built-in or standard data structures and algorithms, such as lists, dictionaries, or sorting functions, whenever possible.

You can measure code quality in WTFs/Minute.

In this article, I have discussed the concept of code readability, why it matters, and how to improve it. I have also looked at some examples of bad and good code in Python, and some tips and best practices for writing readable code. And remember, just because a computer can process your code, doesn't mean it's well-written. The ultimate goal is to write code that not only functions efficiently but is also intuitive and clear to your fellow developers (and your future self). I hope that this article has helped you to understand the importance of code readability, and to write code that humans can understand.

Happy coding!

要查看或添加评论,请登录

Greg Davis的更多文章

社区洞察

其他会员也浏览了