Pure code: causes and effects

Posted by Victor Svirsky, Senior Python Developer / Team Lead, DataArt

How many programmers, so many definitions, what is clean code. When interviewing me, I often hear that good code is one that is easy to read. I agree, but as my personal experience suggests, this is only the tip of the iceberg.

The first call that tells us that the code is no longer clean is an increase in the development time of new functionality and an increase in regression scopes at the slightest change in the system. This is due to the fact that technical debt is accumulating, the components in the system are very closely connected, and there are no autotests. The reasons for this may be:

  • External – such as pressure from the business and its desire to get new functionality faster.
  • Internal – poorly developed development processes and interaction within the team, lack of control and development standards or a banal lack of competence.

You should not put off work on the quality of code and architecture in a long box. During the sprint, it is important to be able to separate tasks that are of direct value to the business (tasks with new functionality) and technical tasks that have only an indirect effect on the business. The proportion of separation depends on the current state of the project, the time frame and the number of free hands.

What is clean code?

It turns out to say that the code is clean and the system is designed correctly, easy reading of the code is not enough. He must possess other qualities:

  • The code is easy to modify. With proper design and architecture, code expansion can do without special time and technical costs. Code entities should not be closely related, the code should be partly abstract and self-contained. Each entity that we operate during development should be responsible only for its part of the functionality.
  • The code must be stable, predictable, safe and reliable. No matter how simple the code is in reading, it should be covered with tests. Good code and tests are always there. Moreover, it is important not only the number of tests, but also their quality. With such code, there are no problems when starting and debugging; it does not cause changes in the environment.
  • Secure code. When writing any code, one should not forget about the general security of the product. I recommend that you familiarize yourself with the basic principles of security and adhere to them. If we are talking about web projects, I recommend OWASP.
  • A good code is code that doesn’t exist. This does not mean that all the code should be written in one line, and you must be proud of subtle methods. This means that the code should not be duplicated, and some of the common things should remain at the level of abstractions. Theoretically, simplification of the code should lead to a decrease in the number of defects.
  • Reading the code itself is also important. Each developer has their own writing style, and the level of reading depends on our experience. We all want to write simple, beautiful, and concise code.

In order to avoid a subjective assessment of the quality of its code, the term “code smells” or “stock code” was introduced in 1961. This is a group of rules and recommendations that clearly define whether it is time to do refactoring. The “odor” leads to code decay, and developers should always strive to eliminate it. The need for refactoring directly follows from the smell of the code, and by preventing the cause, we can avoid the consequences. For more information on the key signs that you should start refactoring, read the book. Martin Fowler Refactoring. Improving existing code. ”

Should I write clean code?

Definitely worth it! But not always and not everywhere it is worth paying too much attention to cleanliness.

Do not forget about the usefulness and life of your code. For example, if you are faced with the task of developing a concept – PoC (Proof of concept), and you prove that the selected technology stack performs the task, your code will become irrelevant in a week or two. It’s not worth the effort to improve this functionality.

There is an opinion that there is no need to monitor the quality of the code or parts of the system that will soon be replaced. And this is not true for several reasons. High quality workmanship will make the transition or integration with new parts easier, more seamless and faster. It will certainly simplify life in cases where several versions of the code have to be supported at the same time. The number of regression errors with clean code will be many times less. Also, do not forget that there is nothing more permanent than temporary. Perhaps the task of improving this part of the code for several months will lie in the backlog.

What will help improve your code?

Most programmers dream of writing code quickly and beautifully, so that everything works perfectly the first time. But not everyone succeeds in making the code not just working, but understandable. How to succeed in writing clean code? There are two ways – self-organization and teamwork.

Self-organization

Consider several possible ways to improve the individual quality of the code. These recommendations are suitable for developers at any level.

  1. Tools

    Pay attention to the tools used, especially the main one – the development environment. A convenient tool is half the success. The IDE (integrated development environment) not only complements the code on the fly, but also suggests places with a smell that are worth putting in order. By expanding the IDE with the necessary plug-ins, you get a Swiss army knife. You spend most of the work in this tool – make it as convenient and flexible as possible.

    Do not miss the opportunity to purchase your favorite product. Fighting licenses will reduce your time, and official support will never be superfluous.

  2. Participation in open source projects

    In teamwork, the ability to work with someone else’s code is important. Understanding, reading, and adhering to style is not always easy. Working with other people’s code, it is often possible to learn about new approaches to solving non-trivial tasks. Read and learn the code!

  3. Strict framework

    Start developing a small project that solves a specific problem. Design your own architecture and implement it. In doing so, you can set yourself technical limitations. For example, development using OOP only, the cyclomatic complexity of methods is not more than 10, following all development recommendations in a given language, deliberate use of design patterns, etc.

    Develop the habit of working within. After all, there will not always be someone who can monitor the quality of your work.

  4. The development of abstract thinking

    Read and use programming patterns. They are not tied to a specific language and help solve problems more efficiently. You will have the same understanding of the design of problem solving with other developers. You will better understand how third-party tools and libraries work.

    Solve programming puzzles. This is a great way to improve your programming skills and learn the intricacies of your chosen language.

  5. Decision analysis

    Do not rush to solve problems head on. Ask questions to senior developers and yourself. It is always important to understand the causal relationship of certain decisions. By understanding the problem well, you can solve it effectively.

    A good developer is not a craftsman who writes code, but an engineer who combines applied research, planning and design in his work.

  6. Reading documentation

    Being able to read documentation is just as important as reading code. The next step is to learn how to write documentation.

  7. Practice!

    Any experience is better than its absence.

Teamwork

Most tasks are solved in a team. It is very important to share responsibility for quality between its participants. The larger the team, the more difficult it is to keep the product in good condition. Let’s consider several approaches of code retention in the above conditions.

  1. Code review

    This is a simple principle for understanding and execution. At least two people, including the author of the code, check the code.

    There are several things to consider when checking your code:

    • One of them is checking if the code violates the rules of the code agreement. This is a process that can and should be automated using static analyzers in CI (continuous integration).
    • Others are code maintainability and error handling that cannot be checked automatically.
    • Last but not least, the code needs to be checked for completeness. Does this piece of code contain the entire volume of the function as intended?

  2. Continuous integration

    The essence of continuous integration is that it allows you to quickly get a lot of feedback on the current status of the code.

    Continuous integration works when you follow two simple rules:

    • Product assembly is quick. Avoid slow builds. Continuous integration improves the quality of the code because it provides fast feedback. If the tests fail, the assembly will fail, you will immediately receive a notification.
    • You add static analyzers to the build script, which check the coding conventions, improve the quality of the code, and verify security.
  3. Coding Conventions

    It is important to have a list of coding conventions. But before you start making a list, everyone on the team must understand the significance of this agreement. Do not expect such an agreement to be adopted the first time, there are a lot of discussions waiting for you.

    Make a list of coding conventions in which you designate how variables should be declared, naming conventions, etc. The number of rules you can add to this list is unlimited and can vary. Just do what works for you and your team. Feel free to add new rules to the list of agreements if this suits the team. The same applies to the removal of agreements from the list.

    Once you have received your list of coding conventions, it is imperative to stick to them. The most preferred way is to check the coding conventions with static analyzers and continuous integration, as it does not require any manual actions.

    Quality code can accelerate long-term software development. It can be reused, and developers do not need to waste time fixing old bugs. It also makes it easier for new people to join the project.

  4. Tests

    The fewer errors in the code, the higher its quality. Careful testing filters out critical errors and ensures that the code works as intended.

    Having a clear testing strategy is important when it comes to improving code quality. At a minimum, your code should be modular. Even better if you want to use other methods, such as integration or regression testing.

    The largest number of tests in a software project should be unit tests. They are cheap and fast. There are many different tools that can help you create unit tests and code coverage reports. Running a test suite and generating a code coverage report can be done automatically through continuous integration. You can even make the build unsuccessful if the code coverage does not match the required percentage.

  5. Error analysis

    Having errors in your code is probably inevitable. Therefore, the analysis and method of handling these errors is very important. If you want to improve your skills, it is important to learn from your own mistakes.

    When an error occurs, analyze it with a few questions:

    • Is this a low or high priority error? If so, it should be fixed immediately. If the error is insignificant and allows the product to perform the task without any problems, such an error can be fixed in the following iterations.
    • Something went wrong?
    • Why haven’t we checked this (correctly)?
    • What other places is this happening?
    • And most importantly – how can we prevent this from happening in the future?

    Of course, there are tools to help you track errors. You can choose among those on the market that tracker that suits your needs.

  6. Metrics collection

    There are several metrics that you can use to quantify the quality of your code. This task is easily handled. Sonarquube. It can easily help you collect all the necessary important metrics:

    • Potential errors

      The number of defects and their severity are important indicators of overall quality. Finding errors can and should be automated, but only in part. The review code remains valid to identify deeper errors in the code logic itself.

    • Repeating code sections

      Each piece of knowledge should have a single, consistent and authoritative representation within the system – the DRY principle (Don’t repeat yourself).

    • Difficulty metrics

      Complexity is often measured using a cyclomatic complexity metric. This is an indicator of the number of linearly independent paths in the program code. There is a correlation between the number of cyclomatic complexity and the frequency of defects. Theoretically, simplification of the code should lead to a decrease in the number of defects.

    • Availability of required comments

      Just a few correctly spaced lines with comments, a comment on a module, class or method will be enough to make the code much easier to understand.

    • The degree of test coverage

      Used when testing software. It shows the percentage of the source code of the program that was executed during the testing process. Set the bar below which the percentage of your tests does not fall.

***

Errors in the code are akin to a carbon footprint. It is completely impossible to escape, and excess exhaust alone will not kill either humanity or its surrounding nature. Nevertheless, it seems a natural need to reduce the negative effect of one’s stay on the planet today. In approximately the same way, writing clean code is the responsibility of every developer. No matter which path you choose, you must strive to write working and understandable code.

Well, if you can not turn purity into a fetish, given the life of our code and evaluating the feasibility of further improvements. The main thing to remember about people: users who can fail even a small part of the system developed by us, and engineers who have to support this system.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *