Introduction To Clean Code PDF
Document Details
Tags
Summary
This document introduces the concept of clean code, emphasizing its importance for maintainability and effectiveness in software development. It explains why clean code is more than just good formatting and touches on tools, examples of clean and unclean code, and the importance of docstrings and annotations for clarity. The document also covers some exceptions where clean code may not be strictly necessary. It's a useful guide for improving code readability and maintainability.
Full Transcript
Introduction, Code Formatting And Tools Introduction We'll start first by understanding what clean code is, and why this is important for a software engineering project for it to be successful We will learn how important it is to maintain good code quality in order to work effici...
Introduction, Code Formatting And Tools Introduction We'll start first by understanding what clean code is, and why this is important for a software engineering project for it to be successful We will learn how important it is to maintain good code quality in order to work efficiently. What clean code mean That clean code really means something far more important than formatting That having standard formatting is a key component in a software project for the sake of its maintainability How to make the code self- documenting by using the features that Python provides How to configure tools to automate static verifications on the code The meaning of clean code Clean code lacks a formal definition and cannot be objectively measured by tools. Its assessment relies on human judgment and professional experience. The primary purpose of programming languages isn't just communication with machines, but also with other developers. The importance of having clean code Clean code is crucial for maintainability, reducing technical debt, enabling successful agile development and continuous delivery. A maintainable codebase is essential for consistent feature delivery, while technical debt, stemming from poor coding decisions, increases future development costs. Some exceptions Hackathons If you're writing a simple script for a one-off task Code competitions When developing a proof of concept When developing a prototype When you're working with a legacy project that will be deprecated, and it's only in maintenance mode for a fixed, short-lived period of time Break Break A In Python, PEP- 8 is the most well-known standard, and that document provides guidelines on how we should write our Code programs, in terms of spacing, naming convention, line length, and more formatting However, clean code is something else that goes far beyond coding standards, formatting, linting tools, and other checks regarding the layout of the code Clean code is about achieving quality software and building a system that is robust and maintainable PEP 8 PEP 8 is a document that provides guidelines and best practices on how to write Python code. The primary focus of PEP 8 is to improve the readability and consistency of Python code. PEP 8 defines coding conventions for the Python code comprising the standard library in the main Python distribution. PEP 8 Here are some of the key rules of PEP 8: Use 4 spaces per indentation level. Use hanging indents for continuation lines. Use lowercase letters for function names and UPPERCASE LETTERS for constants. Use spaces around operators and after commas. Limit all lines to a maximum of 79 characters. Use docstrings to document your code. Implementing a coding style guide on your project Searchability: This refers to the ability to identify tokens in the code at a glance; that is, to search in certain files for the particular string we are looking for Consistency: If the code has a uniform format, the reading of it will be much easier Better error handling: One of the suggestions made in PEP-8 is to limit the amount of code inside a try/except block to the minimum possible Code quality: By looking at the code in a structured fashion, you will become more proficient at understanding it at a glance , and you will spot bugs and mistakes more easily Documentation Code documentation is This section intends to important in Python, explore docstrings and because being dynamically annotations because typed, it might be easy to they're the tools in Python get lost in the values of used to document code variables or objects across functions and methods Code comments Minimize code comments. Well-chosen abstractions and clear naming reduce the need for comments. Comments often signal poorly written code. Documenting design/architecture within the code is positive. Docstrings We can pass something with a.keys method , and it will update the original dictionary with the keys from the object passed per parameter We can pass an iterable of pairs of keys and values, and we will unpack them to update It's also telling us that we can update the dictionary with values taken from keyword arguments Understanding Docstrings in Python What is a Docstring? A docstring is a special string used to document a function, class, or module. It appears right after the definition (before the code block) and provides information on what the function or class does. Purpose of Docstrings To describe the functionality, usage, and purpose of a piece of code. To improve code readability and maintainability. Syntax: def function_name(parameters): """ This is a docstring. It explains the function's purpose, arguments, and return values. """ # Function code Types of Docstrings One-liner Docstrings: Used for simple functions or methods. def add(a, b): """Returns the sum of two numbers.""“ return a + b Multi-line Docstrings: Used for more complex explanations or when documenting parameters and return values. def multiply(a, b): """ Multiplies two numbers. Parameters: a (int, float): The first number. b (int, float): The second number. Returns: int, float: The result of multiplication. ""“ return a * b Annotations PEP 3107 introduced annotations to provide hints about variable and function argument types. Annotations are not enforced but serve as documentation for code readers. Annotations allow specifying expected types for variables. Annotations create reusable abstractions within the codebase. A special __annotations__ attribute stores annotations. Annotations This will give us access to a dictionary that maps the name of the annotations with their corresponding values, which are those we have defined for them We could use this to generate documentation, run validations, or enforce checks in our code if we think we have to Speaking of checking the code through annotations, this is when PEP-484 comes into play Do annotations replace docstrings? before annotations were introduced, the Docstring conventions exist for dynamic and nested data way to document the to standardize the inclusion types, it is always a good types of the of function information, such idea to provide examples of parameters of as parameter types and the expected data so that we functions or attributes meanings, return values, can get a better idea of what and potential exceptions. we are dealing with was to put docstrings on them Tooling Is this code easy to understand and follow to a fellow programmer? Does it speak in terms of the domain of the problem? Would a new person joining the team be able to understand it, and work Checking type consistency Automated type consistency checks are desirable. Python's dynamic typing allows adding optional type annotations for improved readability. Type annotations enable tools to automatically detect common type-related errors (bugs). Tools exist to analyze projects and check for type inconsistencies. Checking type consistency However, the tool is not perfect, so if you think it is reporting a false positive, you can ignore that line with the following marker as a comment: It's important to note that for this or any tool to be useful, we have to be careful with the type annotations we declare in the code Automatic formatting Creating a milestone pull request that will apply the black format to all Alternatively, you can rewrite the history with the changes in the code with the black format applied Setup for automatic checks It will first check the compliance with the coding guideline (PEP-8, or black) Then it will check for the use of types on the code Finally, it will run the tests Clean Code Example In the unclean code example, there is a function named func with parameters a, b, and c. However, the name of the function is not descriptive and doesn't convey its purpose. In the clean code example, the function is renamed to calculate_result, which provides a clear indication of what the function does. Additionally, in the clean code example, the function and parameter names are more meaningful. Instead of using generic names like a, b, and c, it's better to use descriptive names that convey the purpose of each parameter. The logic and structure of the code remain the same in both examples. However, by using meaningful names, the clean code example is easier to read, Summary We now have a first idea of what clean code is, and a workable interpretation of it, which will serve us as a reference point for the rest of this book Clean code is about readability, maintainability of the code, keeping technical debt to a minimum, and effectively communicating our ideas in the code so that others can understand what we intended to write in the first place The next chapter is going to be more focused on Python-specific code, and how to express our ideas in idiomatic Python Annotations vs Docstrings Annotations: Annotations are a way to specify the types of function arguments and return values. Annotations are optional, and they don’t affect the behavior of the function at runtime. Annotations are defined using a colon followed by the type name, like this: def foo(x: int) -> float:. Docstrings: Docstrings are a way to provide documentation for functions or methods. Docstrings are defined as strings that appear as the first statement in a function or method definition. Docstrings can be accessed at runtime using the __doc__ attribute of the function or method In this example, add_numbers is a function that takes two integer arguments (x and y) and returns their sum as an integer. The types of the arguments and return value are specified using annotations. The documentation for the function is provided using a docstring. Python Tools For Clean Code Pycodestyle: Pycodestyle is a Python module that checks your code against the PEP 8 recommendations and delivers a report on where the analyzed code is out of spec. Pycodestyle doesn’t provide automatic fixes for issues, but it is highly configurable, allowing you to suppress specific kinds of errors or parse only specific files in a source tree. Autopep8: Autopep8 uses Pycodestyle to determine what changes need to be made, then reformats code to conform to the suggestions provided. Existing files can be reformatted in place or written to new files. Autopep8 also fixes a host of other issues that can creep in, such as cleaning up code converted from Python 2 to Python 3 or files that have mixed line-ending markers. Flake8: Flake8 wraps up several Python linting and code-style tools in a single package. Along with PyFlakes, which uses syntax checking to detect basic errors, and Pycodestyle, which we discussed above, Flake8 provides an additional tool to check the “cyclomatic complexity” of a project — that is, the number of independent code paths found in the program. Pylint: Pylint is another popular tool for checking Python code quality. It analyzes your code for errors, bugs, and stylistic issues and provides detailed reports on what needs to be fixed. Pylint also supports plugins, so you can extend its functionality as needed. Black: Black is an opinionated code formatter that reformats your Python code to make it more consistent and easier to read. Black takes care of formatting details like indentation, line length, and whitespace automatically, so you don’t have to worry about them. Thanks