There is no single or strict definition of code neatness, and there may be no formal measure of what constitutes code neatness, so you can’t run a tool on a code repository that tells you whether your code is good or bad and how maintainable it is. Of course, you can run checkers, code verifiers, static profilers, and so on. These tools will help you a lot. They are necessary, but they are not enough. Clean code is not up to the machine or the script (so far), but to us as professionals.

For decades, we used the term “programming language” and thought of it as a language that communicates our ideas to a computer, allowing it to run our programs. But we were wrong, and that was only part of the truth. The “real language” behind the programming language is the language that communicates our ideas to other developers.

This is the true essence of clean code. It depends on other developers being able to read and maintain the code. As professionals, we are the only ones who can judge this. Think about it: as developers, we spend a lot more time reading code than actually writing it. Whenever we want to change or add new functionality, we must first read all the context of the code that needs to be modified or extended. A programming language (Python) is a language in which developers communicate with each other.

There are many reasons why keeping your code clean is so important. Most of the reasons have to do with maintainability, reducing technical debt, working effectively with agile development, and managing a successful project.

The first idea we want to explore is about agile development and continuous delivery. A good and maintainable code base is essential if you want your project to deliver features successfully and consistently at a steady and predictable rate.

Suppose you are driving a car on your way to a certain destination, and you want to get there by a certain time. You must estimate when you will arrive at your destination so that you can tell the people who are waiting for you. If the car doesn’t break down and the road is smooth, your estimate is unlikely to be off by much; Conversely, if the road is damaged and you have to get out of your car to move rocks, or avoid cracks, or stop every few kilometres to check the engine, etc., it is unlikely you will be sure when you arrive (or if you will arrive at all). The metaphor is straightforward, and the path here can be understood as code. If you want to move the project forward at a steady, constant, and predictable pace, the code should be maintainable and readable.

Technical debt is software problems that result from compromises or bad decisions. To some extent, we can think of technical debt in two ways. One is from the past to the present, what if the current problems we face were caused by bad code written earlier? Second, from now to the future, if we decide to take shortcuts now, instead of taking the time to find the right solution, what kind of trouble will we get ourselves into in the future?

Debt is the right word. This is a liability because code will be harder to change in the future than it is now. The cost is the interest on the debt. The resulting technical debt means that it is harder and more expensive to change code tomorrow than today, and it will be more expensive the day after tomorrow, and so on.

Once the team fails to deliver something on time and has to stop to fix and refactor the code, the code pays the price of technical debt.

The worst thing about tech debt is that it represents a long-term and fundamental problem. This is not something to be highly alarmed about. Instead, it’s a quiet problem, a problem scattered throughout the entire project, and one day, at a particular time, it will “wake up” and get in the way of moving forward.

The role of code formatting in code neatness

 

Does code neatness mean formatting and structuring code according to some standard (for example, PEP-8 or custom standards defined by the project specification)? Not so.

Code neatness goes far beyond coding standards, formatting, beautification tools, and other checks on code layout. Code cleanliness is about implementing high-quality software and building a robust, maintainable, and technical debt-free system. A piece of code or an entire software component can be 100 percent peP-8 (or any other guideline) compliant and still not meet the above requirements.

However, there are some dangers in not paying attention to the structure of your code. With this in mind, we’ll start by looking at problems with poor code structure and how to fix them, then show you how to configure and use tools for Python projects to automatically check and correct problems.

In summary, we can say that code neatness has nothing to do with PEP-8 or coding style. Clean code means much more than that, and it means much more than maintainability and software quality. However, as you will see, it is important to format your code properly for efficient work.

Follow coding style guidelines in your project

Coding guidelines are the minimum requirements that must be considered when a project is developed under quality standards. In this section, we will explore the reasons behind this. Next, let’s look at how tools can automatically follow coding style guidelines in a project.

Consistency is the first thing that comes to mind when trying to think about finding a good feature in your code layout. We want the code to have a consistent structure that makes it easier to read and understand. If the code is incorrect or structurally inconsistent, and everyone on the team does things their own way, you end up with code that requires extra effort and concentration to understand properly. Such code is easily misunderstood, and any bugs or minor errors that result are likely to go unnoticed.

That’s what we want to avoid. We want code that can be read and understood at a glance.

If members of the development team agree to write code in a standardized way, the resulting code will look more familiar. This way, you can quickly recognize patterns and remember them, making it easier to understand content and detect errors. For example, when something goes wrong in your code, you might see something strange in a pattern you’re familiar with — it catches your attention, and when you look more closely, you’re more likely to spot the error!

An interesting analysis of this, as described in the classic book Code Complete, is in a paper called Perception in Chess (1973), which refers to an experiment to determine how different people understand or remember different Chess games. The experiment looked at different levels of chess players (novice, intermediate and master) and at different positions on the board. They found that novices performed just as well as chess masters when the positions of the pieces were random. Since this is just a memory exercise, anyone can perform at a reasonable level. But when the positions of the pieces follow some logical order that might occur in a real game (or, if certain consistency is observed, certain patterns are adhered to), chess masters perform much better than others.

Now imagine that the same applies to software development. As expert software engineers in Python, we are like the chess masters in the example above. If the structure of the code is random, doesn’t follow any logic, or doesn’t follow any standards, we’re like a novice developer, and it’s hard to spot errors; If we get used to reading code in a structured way and learn to get ideas out of code quickly by following this pattern, we will have an advantage over other developers in project development.

As far as Python is concerned, the coding style you should follow is PEP-8. You can extend it or adopt parts of it to accommodate a particular aspect of the project you’re working on (line lengths, comments on strings, etc.). However, we recommend that whether you use the original version of the PEP-8 specification or extend it, you stick with it rather than try a different standard from scratch.

This is because PEP-8 takes full account of the many specificities of Python syntax (often not applicable to other languages), and it was created by core Python developers who contributed to Python syntax. As a result, we believe that other standards are actually hard to match, let alone surpass, PEP-8.

In particular, PEP-8 has some nice improvements when it comes to handling code.

(1) Grep can be performed. This is the ability to grep content in your code, that is, to search certain files (and parts of those files) for the particular string you are looking for. One of the features introduced by PEP-8 is the distinction between how value assignments are written to variables and how keyword arguments are passed to functions.

To better understand this, let’s illustrate it with an example. Suppose we are debugging and need to find where the value of a parameter named location is passed. You can run the following grep command to get the file and line number for what you’re looking for.

$ grep -nr "location=" .
./core.py:13: location=current_location,
Copy the code

Now, if we want to know where the variable is assigned the value, we can run the following command.

$ grep -nr "location =" .
./core.py:10: current_location = get_location()
Copy the code

Pep-8 establishes a convention that does not use Spaces when passing arguments to functions through keywords, but uses Spaces when assigning variables. Therefore, we can adjust the search criteria (the first search has no space on either side of the equals sign, and the second search has a space on either side) to make the search more efficient. That’s one of the benefits of keeping an appointment.

(2) Consistency. If the code appears to have a uniform format, it’s much easier to read. This is especially important for people who are new to the project, because if you want new developers to join the project, or if you want to hire new (and possibly inexperienced) programmers to the team, they will have to be familiar with the code (and may even consist of multiple code repositories). Their job is made easier if the code format, documentation, naming conventions, and so on are the same across all files in all code repositories.

(3) Code quality. By looking at the code in a structured way, you suddenly understand it more skillfully (as in Perception in Chess) and find bugs and errors in the program more easily. In addition, tools that check code quality can also indicate potential errors. Static analysis of code can help reduce the error rate per line of code.

This article is from Writing Clean Python Code

 

This is a book about Python software engineering principles.

There are many books on software engineering and many resources available on Python, but there is still a lot of work to do to bring the two together. This book is an attempt to build a bridge between them.

It is impossible to cover all the topics of software engineering in one book, because the field is so broad and there are books devoted to a particular topic. This book focuses on the main practices and principles of Python software engineering. It aims to help you write code that is easier to maintain and to take advantage of Python’s features to write code.

Chapter to feed

Chapter 1 introduces you to the main tools you need to set up a Python development environment, the basics Python developers need to know when starting out with the language, and some guidelines for maintaining code readability in your projects, such as tools for static analysis, documentation, type checking, and code formatting.

Chapter 2, Python-style code, introduces the first idiom in Python — which we’ll continue to use in subsequent chapters. This chapter also introduces some of Python’s unique features and how to use them, and begins a discussion of how Python-style code can lead to better code quality.

Chapter 3, general characteristics of Good Code, reviews the general principles of software engineering to help you write maintainable code. This chapter discusses this topic and applies these principles using tools in the Python language.

Chapter 4, SOLID Principles, introduces the SOLID principles of object-oriented software design. SOLID is the industry term for software engineering, namely SRP, OCP, LSP, ISP, and DIP. This chapter shows how these five principles are applied in Python. Suffice it to say, given the nature of the Python language, not all methods are perfectly applicable.

Chapter 5, improving code with decorators, introduces one of Python’s biggest features, decorators. Now that we know how to create decorators (for functions and classes), we use them for code reuse, separation of responsibilities, and creating more fine-grained functions.

Chapter 6 uses descriptors to extract more information from objects and explores descriptors in Python, which take object-oriented design to a new level. Although this is more of a framework – and tool-specific feature, we can see how descriptors can be used to improve code readability, and how code can be reused.

Chapter 7, using generators, shows that generators are probably Python’s best feature. In fact, iteration is a core component of Python, which leads us to believe that it leads to a new programming paradigm. In general, by using generators and iterators, we can think about the way we write programs. Based on what we’ve learned from generators, we’ll take a closer look at coroutines in Python and the basics of asynchronous programming.

Chapter 8, Unit Testing and Refactoring, discusses the importance of unit testing in any so-called “maintainable code base.” This chapter reviews the importance of unit testing and explores the main frameworks for unit testing (UnitTest and PyTest).

Chapter 9 common Design Patterns reviews how to implement the most common design patterns in Python, not from a problem solving perspective, but by looking at how to solve problems with better and more maintainable solutions. This chapter mentions features of Python that make some design patterns invisible, and takes a practical approach to implementing some of them.

Chapter 10 clean Architecture emphasizes that code cleanliness is the foundation of a good architecture. All of the details we covered in Chapter 1, and others we reviewed along the way, will play a key role in the overall design when deploying the system.