0% found this document useful (0 votes)
18 views

3 - Code Formatting Tools

Uploaded by

arora.2003.karan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

3 - Code Formatting Tools

Uploaded by

arora.2003.karan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Code Formatting Tools

Code Formatting Tools are an essential part of modern software development,


ensuring that code is not only functional but also readable and maintainable. These
tools automate the process of applying a consistent style to code, which is
particularly important in collaborative environments where multiple developers
contribute to the same codebase.

Key benefits include:

 Improved Readability: By standardizing indentation, spacing, and other


stylistic choices, code becomes easier to understand at a glance.
 Easier Maintenance: Consistent formatting reduces the cognitive load
when switching between different parts of the code or when onboarding new
team members.
 Better Version Control: They help avoid merge conflicts caused by
differing code styles and make diffs cleaner and more relevant.

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.

1. Readability and maintenance: Clean code prioritizes clarity, which makes


reading, understanding, and modifying code easier. Writing readable code reduces
the time required to grasp the code's functionality, leading to faster development
times.

2. Team collaboration: Clear and consistent code facilitates communication and


cooperation among team members. By adhering to established coding
standards and writing readable code, developers easily understand each other's
work and collaborate more effectively.

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.

4. Improved quality and reliability: Clean code prioritizes following established


coding standards and writing well-structured code. This reduces the risk of
introducing errors, leading to higher-quality and more reliable software down the
line.

Now that we understand why clean code is essential, let's delve into some best
practices and principles to help you write clean code.

Principles of Clean Code


Like a beautiful painting needs the right foundation and brushstrokes,
well-crafted code requires adherence to specific principles. These
principles help developers write code that is clear, concise, and,
ultimately, a joy to work with.
Avoid Hard-Coded Numbers
Use named constants instead of hard-coded values. Write constants with
meaningful names that convey their purpose. This improves clarity and
makes it easier to modify the code.
Example:
The example below uses the hard-coded number 0.1 to represent a 10%
discount. This makes it difficult to understand the meaning of the
number (without a comment) and adjust the discount rate if needed in
other parts of the function.
Before:
def calculate_discount(price):
discount = price * 0.1 # 10% discount
return price - discount
The improved code replaces the hard-coded number with a named
constant TEN_PERCENT_DISCOUNT. The name instantly conveys the
meaning of the value, making the code more self-documenting.
After :
def calculate_discount(price):
TEN_PERCENT_DISCOUNT = 0.1
discount = price * TEN_PERCENT_DISCOUNT
return price - discount
Also, If the discount rate needs to be changed, it only requires
modifying the constant declaration, not searching for multiple instances
of the hard-coded number.

2. Use Meaningful and Descriptive Names


Choose names for variables, functions, and classes that reflect their
purpose and behavior. This makes the code self-documenting and easier
to understand without extensive comments.
Example:
If we take the code from the previous example, it uses generic names
like "price" and "discount," which leaves their purpose ambiguous.
Names like "price" and "discount" could be interpreted differently
without context.
Before:
def calculate_discount(price):
TEN_PERCENT_DISCOUNT = 0.1
discount = price * TEN_PERCENT_DISCOUNT
return price - discount

Instead, you can declare the variables to be more descriptive.


After:
def calculate_discount(product_price):
TEN_PERCENT_DISCOUNT = 0.1
discount_amount = product_price * TEN_PERCENT_DISCOUNT
return product_price - discount_amount
This improved code uses specific names
like "product_price" and "discount_amount," providing a clearer
understanding of what the variables represent and how we use them.
3. Use Comments Sparingly, and When You
Do, Make Them Meaningful
You don't need to comment on obvious things. Excessive or unclear
comments can clutter the codebase and become outdated, leading to
confusion and a messy codebase.
Example:
Before:
def group_users_by_id(user_id):
# This function groups users by id
# ... complex logic ...
# ... more code …
The comment about the function is redundant and adds no value. The
function name already states that it groups users by id; there's no need
for a comment stating the same.
Instead, use comments to convey the "why" behind specific actions or
explain behaviors.
After:
def group_users_by_id(user_id):
"""Groups users by id to a specific category (1-9).

Warning: Certain characters might not be handled correctly.


Please refer to the documentation for supported formats.

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 …

This comment provides meaningful information about the function's


behavior and explains unusual behavior and potential pitfalls.
4. Write Short Functions That Only Do One Thing
Follow the single responsibility principle (SRP), which means that a
function should have one purpose and perform it effectively. Functions
are more understandable, readable, and maintainable if they only have
one job. It also makes testing them very easy.

If a function becomes too long or complex, consider breaking it into


smaller, more manageable functions.
Example:

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

6. Follow Established Code-Writing Standards


Know your programming language's conventions in terms of spacing,
comments, and naming. Most programming languages have community-
accepted coding standards and style guides, for example, PEP 8 for
Python and Google JavaScript Style Guide for JavaScript.
Here are some specific examples:

 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.

Also, consider extending some of these standards by creating internal


coding rules for your organization. This can contain information on
creating and naming folders or describing function names within your
organization.
7. Encapsulate Nested Conditionals into
Functions
One way to improve the readability and clarity of functions is to
encapsulate nested if/else statements into other functions. Encapsulating
such logic into a function with a descriptive name clarifies its purpose
and simplifies code comprehension. In some cases, it also makes it
easier to reuse, modify, and test the logic without affecting the rest of
the function.
In the code sample below, the discount logic is nested within
the calculate_product_discount function, making it difficult to
understand at a glance.
Example:
Before:
def calculate_product_discount(product_price):
discount_amount = 0
if product_price > 100:
discount_amount = product_price * 0.1
elif price > 50:
discount_amount = product_price * 0.05
else:
discount_amount = 0
final_product_price = product_price - discount_amount
return final_product_price
We can clean this code up by separating the nested if/else condition that
calculates discount logic into another function
called get_discount_rate and then calling the get_discount_rate in
the calculate_product_discount function. This makes it easier to read at
a glance.
The get_discount_rate is now isolated and can be reused by other
functions in the codebase. It’s also easier to change, test, and debug it
without affecting the calculate_discount function.
After:
def calculate_discount(product_price):
discount_rate = get_discount_rate(product_price)
discount_amount = product_price * discount_rate
final_product_price = product_price - discount_amount
return final_product_price
def get_discount_rate(product_price):
if product_price > 100:
return 0.1
elif product_price > 50:
return 0.05
else:
return 0

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:

 External Documentation: Such as user manuals, technical specifications,

design documents, and coding guidelines.

 Internal Documentation: Comments within the code, explaining how

functions, classes, and modules work.

 High-Level Overviews: Descriptions of the overall architecture, purpose, and

functionality of the software.


Types of Code Documentation
Not all code documentation is the same. Collectively, all code
documentation helps contribute to building and maintaining a
comprehensive understanding of the codebase over time. However,
different types of code documentation serve various purposes and
audiences.

 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.

 Configuration files, such as YAML, JSON, or XML files, are often


used to store a software project's settings, preferences, or other
configuration data. Documentation within these files helps users
understand the purpose and format of each configuration option,
facilitating customization and configuration.

 Documentation Strings (Docstrings) are special code comments


embedded within code to document classes, functions, or modules in a
structured format. They typically describe the entity, its parameters,
return values, and usage examples. Docstrings can be automatically
extracted to generate API documentation or viewed interactively within
integrated development environments (IDEs).

 Class/Module API documentation describes the classes or modules in


a codebase, including their purpose, functionality, attributes, methods,
and any relevant usage examples. It typically provides an overview of
the available classes or modules and how they interact with each other.

 Method/Function API documentation focuses on individual methods


or functions within a class or module. It explains the purpose of each
method, its parameters, return values, and any exceptions it may raise.
This type of documentation helps developers understand how to use
specific functions correctly.
 The README.md file typically resides in the root directory of the
project repository. A README file details the project's purpose,
installation instructions, usage examples, and other relevant information
for developers or users. A README file is often written in Markdown
format—a lightweight markup language with plain-text formatting
syntax—for easy formatting and readability.

Popular Code Documentation Tools


Another highly recommended best practice for better code
documentation is using automated tools to help aid the process.
Here are some excellent tools and frameworks that you can use for
generating code documentation in various formats while saving time and
ensuring that your document remains consistent:

 Sphinx is a documentation tool widely used in the Python community


that supports various markup languages (including reStructuredText and
Markdown) and integrates with popular programming languages like
Python, C/C++, and JavaScript. Sphinx can generate documentation in
multiple formats, including HTML, PDF, and ePub.

 Javadoc is a documentation generation tool for Java projects that uses


special comments (Javadoc comments) embedded within Java code to
generate API documentation in HTML format. Javadoc is commonly
used to document Java classes, interfaces, and methods.

 JSDoc is a documentation generation tool for JavaScript projects that


uses special comments (JSDoc comments) embedded within JavaScript
code to generate API documentation in HTML format. JSDoc supports
documenting functions, classes, variables, and more.

 Doxygen is a documentation generation tool that supports multiple


programming languages, including C++, C, Java, Python, and more. It
can generate documentation from source code comments in various
formats, including HTML, LaTeX, RTF, and PDF. Doxygen is known
for its flexibility and extensive customization options.
 Swagger (now known as OpenAPI) is a framework for designing,
documenting, and testing RESTful APIs. It allows developers to define
API specifications using a JSON or YAML format, which can then be
used to generate interactive API documentation.

 GitBook is a documentation platform that allows you to write and


publish documentation using Markdown or AsciiDoc. It provides a user-
friendly interface for writing documentation, version control integration
(with Git), and publishing documentation as websites or eBooks.
 Various Markdown-based tools and frameworks, such
as MkDocs , VuePress , and Docusaurus , allow you to create
documentation websites from Markdown files. These tools provide
themes, navigation structures, and other features to create professional-
looking documentation sites with minimal effort.

 Various (IDE) plugins or extensions can assist with code


documentation. For example, Visual Studio Code (which also integrates
with Codacy ) has extensions like vscode-docs , which provides features
for generating and previewing Markdown documentation.

You might also like