3 - Code Formatting Tools
3 - Code Formatting Tools
Code formatting tools are software applications or plugins that can automatically format your
code to predefined rules or standards. These tools can help you enforce a consistent coding
style across your team, avoid syntax errors, and make debugging easier.
Popular code formatting tools include Prettier, ESLint, Black, and RuboCop.
Prettier is a code formatter that supports multiple languages and integrates with
various editors and tools. It has many options to customize your preferences.
ESLint is a code linter that detects and fixes problems in JavaScript code such as
indentation, spacing, semicolons, etc. It also enforces best practices and coding
conventions.
Black is a code formatter for Python which produces consistent and readable code
with minimal configuration.
RuboCop is a linter and formatter for Ruby that checks and corrects your code for
syntax, style, performance, and security issues. It follows various Ruby style guides
and has a wide range of options and extensions.
(https://www.geeksforgeeks.org/online-code-formatter/)
Writing Clean and Maintainable Code
Clean code is a term used to refer to code that is easy to read, understand, and
maintain. It was made popular by Robert Cecil Martin, also known as Uncle Bob,
who wrote "Clean Code: A Handbook of Agile Software Craftsmanship" in 2008.
In this book, he presented a set of principles and best practices for writing clean
code, such as using meaningful names, short functions, clear comments, and
consistent formatting.
Ultimately, the goal of clean code is to create software that is not only functional
but also readable, maintainable, and efficient throughout its lifecycle.
Why Is Clean Code Important?
When teams adhere to clean code principles, the code base is easier to read and
navigate, which makes it faster for developers to get up to speed and start
contributing. Here are some reasons why clean code is essential.
3. Debugging and issue resolution: Clean code is designed with clarity and
simplicity, making it easier to locate and understand specific sections of the
codebase. Clear structure, meaningful variable names, and well-defined functions
make it easier to identify and resolve issues.
Now that we understand why clean code is essential, let's delve into some best
practices and principles to help you write clean code.
Args:
user_id (str): The user id to be grouped.
Returns:
int: The category number (1-9) corresponding to the user id.
Raises:
ValueError: If the user id is invalid or unsupported.
"""
# ... complex logic ...
# ... more code …
Before:
def process_data(data):
# ... validate users...
# ... calculate values ...
# ... format output …
This function performs three tasks: validating users, calculating values,
and formatting output. If any of these steps fail, the entire function fails,
making debugging a complex issue. If we also need to change the logic of
one of the tasks, we risk introducing unintended side effects in another
task.
Instead, try to assign each task a function that does just one thing.
After:
def validate_user(data):
# ... data validation logic ...
def calculate_values(data):
# ... calculation logic based on validated data ...
def format_output(data):
# ... format results for display …
The improved code separates the tasks into distinct functions. This results
in more readable, maintainable, and testable code. Also, If a change needs
to be made, it will be easier to identify and modify the specific function
responsible for the desired functionality.
5. Follow the DRY (Don't Repeat Yourself)
Principle and Avoid Duplicating Code or Logic
Avoid writing the same code more than once. Instead, reuse your code
using functions, classes, modules, libraries, or other abstractions. This
makes your code more efficient, consistent, and maintainable. It also
reduces the risk of errors and bugs as you only need to modify your
code in one place if you need to change or update it.
Example:
Before:
def calculate_book_price(quantity, price):
return quantity * price
def calculate_laptop_price(quantity, price):
return quantity * price
In the above example, both functions calculate the total price using the
same formula. This violates the DRY principle.
We can fix this by defining a single calculate_product_price function
that we use for books and laptops. This reduces code duplication and
helps improve the maintenance of the codebase.
After:
def calculate_product_price(product_quantity, product_price):
return product_quantity * product_price
Java:
o Use camelCase for variable, function, and class names.
o Indent code with four spaces.
o Put opening braces on the same line.
Python:
o Use snake_case for variable, function, and class names.
o Use spaces over tabs for indentation.
o Put opening braces on the same line as the function or class declaration.
JavaScript:
o Use camelCase for variable and function names.
o Use snake_case for object properties.
o Indent code with two spaces.
o Put opening braces on the same line as the function or class declaration.
8 Refactor Continuously
Regularly review and refactor your code to improve its structure, readability, and
maintainability. Consider the readability of your code for the next person who will
work on it, and always leave the code base cleaner than you found it.
9. Use Version Control
Version control systems meticulously track every change made to your
codebase, enabling you to understand the evolution of your code and revert to
previous versions if needed. This creates a safety net for code refactoring and
prevents accidental deletions or overwrites.
Use version control systems like GitHub, GitLab, and Bitbucket to track changes to
your codebase and collaborate effectively with others.
Code documentation and commenting
Code documentation refers to a collection of documents
and code comments that explain how code works and how to
use it. Let’s break it down:
Code Comments:
1. Code comments are annotations within the source code itself.
2. They provide context, explanations, or clarifications about
specific code sections.
3. Developers use comments to make the code more
understandable for themselves and others.
4. Common types of code comments include single-line comments
(starting with //) and multi-line comments (starting with /* and
ending with */).
5. While comments are essential, they are not the same as
comprehensive documentation.
Code Documentation:
1. Code documentation goes beyond comments and provides a
broader understanding of the entire codebase.
2. It includes:
Code comments are inline annotations within the code that explain its
logic, clarify complex sections, or provide context for future developers.
They are the simplest form of documentation and supplement other,
more detailed forms by offering insights into specific code segments or
algorithms.