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

Class 2 KRM Clean Code

Uploaded by

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

Class 2 KRM Clean Code

Uploaded by

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

Meaningful

Names…
Enhancing Code Readability Through
Effective Naming

# © 2024 Samarth Amrute. All rights reserved.


What Are Intention-Revealing Names?
• Intention-revealing names are names for variables, functions, and classes that clearly
show what they are used for. They make it easy to understand what the code is doing just
by reading the names.

• Why It Matters:
• Easy to Understand: When names are clear, you don’t need to guess what they are used
for. You can understand the purpose of the code quickly.
• Easier to Work With: If you or someone else needs to make changes to the code later,
it’s much easier when the names are descriptive.
• Better Teamwork: Good names help everyone on the team understand the code, even if
they didn't write it themselves.

# © 2024 Samarth Amrute. All rights reserved.


Example 1: Poor
Variable Names
• Problem: The names a and b don’t tell
us what these variables represent. It’s
unclear what the numbers 10 and 20 are
for.
• Benefit: The names userAge and
adminAge clearly describe what the
variables hold. We know userAge is the
age of a user and adminAge is the age of
an admin.

# © 2024 Samarth Amrute. All rights reserved.


Example 2: Poor
Method Names
• Problem: The method name doStuff() is
too vague. It doesn’t explain what the
method actually does or what it is used
for.
• Benefit: The name calculateTotalPrice()
clearly describes what the method does.
It tells us that the method calculates the
total price, making it easier to
understand its purpose.

# © 2024 Samarth Amrute. All rights reserved.


Example 3: Variable
Name Confusion
• Problem: The name temp is unclear. It
doesn’t specify what the number 30
represents. It could be temperature,
temporary data, or something else.
• Benefit: The name
temperatureInCelsius clearly describes
that this variable holds a temperature
value in Celsius. It’s easy to understand
what the number 30 represents.

# © 2024 Samarth Amrute. All rights reserved.


What Does This Mean?
Make
Meaningful Making Meaningful Distinctions: Use
Distinctions different names to clearly differentiate
between variables, methods, or
classes that serve different purposes.
This avoids mixing up similar items.

# © 2024 Samarth Amrute. All rights reserved.


Examples…
• Problem: Both data and info are
used for the same value, which can
be confusing.
• Benefit: userName and adminName
clearly show the difference between
the names of a user and an admin,
making it easy to understand their
distinct roles.

# © 2024 Samarth Amrute. All rights reserved.


What Does This Mean?

Use
Pronounceable
Names..
Pronounceable Names: Use
names that are easy to say out
loud. This makes it easier to
discuss your code with others
and reduces mistakes.
# © 2024 Samarth Amrute. All rights reserved.
Example..
• Problem: cnt is hard to pronounce and
understand quickly.
• Benefit: itemCount is easy to say and
understand. It clearly describes what the
variable represents.
• Why It Matters:
• Easier Communication: Pronounceable
names help when you need to explain your
code to others.
• Reduced Errors: Names that are easy to
say are less likely to cause
misunderstandings or mistakes in coding.
# © 2024 Samarth Amrute. All rights reserved.
Avoid Encodings and Mental Mappings

Avoid Encodings:
Don’t use abbreviations
or shortcuts that make
What Does This
you think hard to figure
Mean?
out what they mean.
Use full, descriptive
names instead.

# © 2024 Samarth Amrute. All rights reserved.


Example..
• Problem: usrNm is an encoded name
that requires extra effort to understand.
Is it "user name"? "user number"? It’s
unclear.
• Benefit: userName is clear and
descriptive. It immediately tells you that
it represents the name of a user.

# © 2024 Samarth Amrute. All rights reserved.


Difference Between Smart
and Professional
Programmers.
• Smart Programmer:
• Characteristics:
• Quick to Solve Problems: Uses clever solutions and
hacks to solve problems quickly.
• Focuses on Short-Term Solutions: Often prioritizes
immediate results over long-term maintainability.
• Good with Technical Skills: Excellent at using
advanced techniques and tools.
• Potential Downsides:
• Code May Be Hard to Maintain: Smart solutions
can sometimes be complex and difficult for others to
understand.
• Short-Term Focus: May overlook long-term
implications and best practices.
# © 2024 Samarth Amrute. All rights reserved.
Difference Between Smart
and Professional
Programmers.
• Professional Programmer:
• Characteristics:
• Focuses on Code Quality: Writes clean, maintainable,
and well-documented code.
• Follows Best Practices: Adheres to coding standards
and best practices to ensure code is robust and scalable.
• Considers Long-Term Impact: Thinks about how code
will be maintained and extended over time.
• Benefits:
• Easier Maintenance: Code is easier to understand and
maintain, leading to fewer bugs and easier updates.
• Better Team Collaboration: Professional code is more
readable and understandable by others, enhancing team
productivity.
# © 2024 Samarth Amrute. All rights reserved.
Class and Method
Names
Class Names:
What To Do:
• Use names that clearly describe what the class
represents. Typically, class names should be
nouns and written in CamelCase (e.g.,
UserAccount, ProductList).
• Examples: Good Example: CustomerManager
• Explanation: Clearly describes a class that
manages customers.
• Bad Example: DataProcessor
• Explanation: Too vague. It’s unclear what
kind of data or processing is involved.

# © 2024 Samarth Amrute. All rights reserved.


Functions: Function Size Matters

What Does This Mean?

• Function Size: Refers to the amount of code within a function.


Functions should ideally be small and focused on performing a single
task or operation.
Why Keep Functions Small?

• Clarity: Smaller functions are easier to read and understand because


they do one thing at a time.
• Maintainability: Easier to update or fix small functions without
affecting other parts of the code.
• Testability: Small functions are easier to test because they have fewer
responsibilities.

# © 2024 Samarth Amrute. All rights reserved.


Example..
• Problem: processOrder() is doing too
many things, making it complex and
hard to manage.
• Benefit: Each function has a single
responsibility, making the code clearer
and easier to maintain.

# © 2024 Samarth Amrute. All rights reserved.


Blocks and
Indenting
What Are Blocks and Indenting?
• Blocks: Sections of code grouped together, typically
enclosed by curly braces {} in many programming
languages.
• Indenting: The practice of using spaces or tabs to align
code, showing the structure and hierarchy of blocks.
Why Proper Indenting Matters:
• Readability: Proper indentation makes the structure of your
code clear and easier to follow.
• Maintainability: Consistent indentation helps in
understanding the code’s logic and flow, making it easier to
update and debug.
• Avoid Errors: Many programming languages use
indentation to define the scope of loops, conditionals, and
functions. Incorrect indentation can lead to errors.
# © 2024 Samarth Amrute. All rights reserved.
Example..
• Problem: Inconsistent indentation
makes it hard to understand the
structure and logic.
• Benefit: Consistent indentation
makes the code easy to read and
understand.

# © 2024 Samarth Amrute. All rights reserved.


Do Only One Thing
Within a Function
What Does This Mean?
• Single Responsibility Principle: A function should
perform one specific task or operation. This makes the
function easier to understand and maintain.
Why It’s Important:
• Clarity: Functions that do one thing are clearer and
easier to read. You can quickly understand what the
function does.
• Maintainability: Easier to update or fix a function when
it has a single responsibility. Changes are less likely to
impact other parts of the code.
• Reusability: Functions that perform a single task can be
reused in different parts of the code without
modification.
# © 2024 Samarth Amrute. All rights reserved.
One Level of Abstraction
Per Function
What Does This Mean?
• Abstraction Level: Refers to how much detail a function
deals with. A function should operate at a single level of
abstraction, meaning it should not mix high-level operations
with low-level details.
Why It’s Important:
• Readability: Functions that operate at one level of
abstraction are easier to understand because they don’t mix
different levels of detail.
• Maintainability: Makes it easier to manage and update
functions when they focus on a single level of abstraction.
• Encapsulation: Helps in hiding complexity and exposing
only necessary parts, making code more modular and
understandable.
# © 2024 Samarth Amrute. All rights reserved.
Example..
• Problem: The function mixes high-level
logic with low-level error handling,
which complicates understanding.
• Benefit: processOrder() handles high-
level logic, while handleError() focuses
on low-level error handling, keeping
each function at a single level of
abstraction.

# © 2024 Samarth Amrute. All rights reserved.


Use Descriptive
Names
What Does This Mean?
• Descriptive Names: Use names for variables,
functions, and classes that clearly describe their
purpose or role. This makes your code more readable
and self-explanatory.
Why It’s Important:
• Clarity: Descriptive names make it easier to
understand what each part of your code does without
needing additional comments or explanations.
• Maintenance: Makes it simpler to update or debug
code because the purpose of each variable or function
is clear.
• Collaboration: Helps team members quickly grasp
the code’s functionality, improving teamwork and
communication. # © 2024 Samarth Amrute. All rights reserved.
Example…
• Problem: The function name calc and
parameters a and b are vague and don’t
describe what the function does.

• Benefit: ‘calculateTotalPrice’ and the


parameters ‘itemPrice’ and ‘taxRate’
clearly describe the function’s purpose
and its inputs.

# © 2024 Samarth Amrute. All rights reserved.


Function Arguments
What Are Function Arguments?
• Function Arguments: Values passed to a function to
provide the input needed for the function to perform its
task. They allow functions to operate on different data.
Why Have Fewer Arguments?
• Simplicity: Fewer arguments make functions easier to
understand and use. It’s clear what data the function
needs.
• Maintainability: Functions with fewer arguments are
easier to modify. Changes in function signatures are
less likely to break other parts of the code.
• Avoid Complexity: Too many arguments can make
functions confusing and harder to track.

# © 2024 Samarth Amrute. All rights reserved.


Example…
• Problem: The function createUser
has too many arguments, which can
be overwhelming and hard to
manage.
• Benefit: By using a single
userDetails argument (possibly a
dictionary or object), the function is
simpler and easier to understand.

# © 2024 Samarth Amrute. All rights reserved.


Command Query
Separation
What Is Command Query Separation?
• Command: A function or method that performs an action or changes the
state of an object. It does not return a value but instead executes an
operation.
• Query: A function or method that retrieves data or provides information
without changing the state of an object. It returns a value.
Why It’s Important:
• Clarity: Separating commands and queries makes your code more
understandable by clearly defining what each function does: one
performs actions, the other retrieves information.
• Predictability: Avoids side effects in queries, ensuring that functions
that retrieve data do not alter the state, which makes the behavior of
your code more predictable.
• Testing: Makes it easier to test functions because you can test queries
for correct data retrieval and commands for correct actions separately.
# © 2024 Samarth Amrute. All rights reserved.
Example..
• Problem: Combines both querying
and updating in one function, mixing
responsibilities.

• Benefit: Clearly separates querying


(getting user) from actions (updating
and saving), improving clarity and
maintainability.

# © 2024 Samarth Amrute. All rights reserved.


Prefer Exceptions to
Returning Error Codes
What Are Error Codes?
• Error Codes: Traditional method where functions return specific values
to indicate an error, often requiring additional logic to handle the errors.
• What Are Exceptions?
• Exceptions: Mechanism that interrupts normal flow of code when an
error occurs. Allows you to handle errors in a centralized way, making
code cleaner and easier to manage.
Why Use Exceptions Instead of Error Codes?
• Clarity: Exceptions clearly separate error-handling logic from the main
code, making it easier to understand.
• Maintainability: Easier to update and maintain code with exceptions
because you handle errors in one place.
• Readability: Reduces clutter by avoiding the need to constantly check
for error codes.
# © 2024 Samarth Amrute. All rights reserved.
Example…
• Problem: The main logic is mixed
with error handling, making the code
less clear.
• Benefit: Separates error-handling
logic from the main code, making it
cleaner and easier to follow.

# © 2024 Samarth Amrute. All rights reserved.


Extract Try/Catch
Block
What Are Try/Catch Blocks?
• Try Block: Code that might throw an exception is placed
inside a try block.
• Catch Block: Handles the exception if it occurs, placed
inside a catch or except block (depending on the
programming language).
Why Extract Them?
• Focus: Keeping try/catch blocks short and extracting the
main logic into separate functions makes code cleaner and
easier to understand.
• Maintainability: Makes it easier to modify or update the
main logic without dealing with exception-handling code.
• Readability: Improves the readability of the code by
separating error handling from the main functionality.
# © 2024 Samarth Amrute. All rights reserved.
Example..
• Problem: The try block mixes the
core logic with exception handling,
making it harder to read and
maintain.
• Benefit: The handleOperation
function encapsulates the logic, while
the try/catch block focuses solely on
handling exceptions, making the
code cleaner and easier to manage.

# © 2024 Samarth Amrute. All rights reserved.


Error Handling Is
One Thing
• What Does This Mean?
• Single Responsibility: Each function should handle only one
aspect of your program. If a function is responsible for both
the main logic and error handling, it’s doing too much.
• Error Handling: Should be treated as a separate
responsibility, often delegated to specific functions or sections
of code.
• Why It’s Important:
• Clarity: Separating error handling from other logic makes
your code easier to read and understand.
• Maintainability: Simplifies updates and modifications since
each function has a clear and focused purpose.
• Testability: Functions that only handle errors are easier to test
in isolation.
# © 2024 Samarth Amrute. All rights reserved.
Example..
• Problem: The function handles both
error checking and data processing,
making it less clear and harder to
maintain.
• Benefit: validateData handles the
error, while processData focuses on
its primary responsibility, making the
code cleaner and more maintainable.

# © 2024 Samarth Amrute. All rights reserved.


Comments: Good
Comments
• Why Are Comments Important?
• Explanation: Comments explain the "why" behind code,
helping others (and your future self) understand its
purpose and logic.
• Clarity: Good comments clarify complex code, making it
easier to understand and maintain.
• Characteristics of Good Comments:
• Necessary: Only add comments where the code’s intent is
not obvious.
• Clear and Concise: Keep comments short and to the
point.
• Descriptive: Explain the reasoning behind decisions, not
just what the code does.
# © 2024 Samarth Amrute. All rights reserved.
Example..
• Problem: The comment states the
obvious, adding no value.
• Benefit: The comment explains why
a discount is applied, providing
useful context for anyone reading the
code.

# © 2024 Samarth Amrute. All rights reserved.


Good Names Can Obviate Comments
The Power of Good Naming:
• Self-Explanatory Code: When variables, functions, and classes have clear and descriptive
names, the code explains itself, reducing the need for comments.
• Improved Readability: Good names make the code easier to read and understand at a
glance.
How Good Names Reduce the Need for Comments:
• Descriptive Names: Names should convey intent, making the purpose of the code
obvious.
• Consistency: Using consistent naming conventions helps maintain clarity across the
codebase.

# © 2024 Samarth Amrute. All rights reserved.


Example…
• Problem: The function name and
variables are vague, requiring a
comment to explain what it does.
• Benefit: The function and variables
are named descriptively, so the code
is self-explanatory and doesn’t need
a comment.

# © 2024 Samarth Amrute. All rights reserved.


Types of Good Comments: Legal Comment
What Are Legal Comments?
• Legal Comments: These are comments that provide information about legal
matters such as copyright notices, licenses, or any other legal obligations.
• Purpose: They ensure that the code complies with legal requirements and that
users are aware of their rights and responsibilities.
When to Use Legal Comments:
• Copyright Notices: Include copyright information to protect intellectual property.
• Licenses: Specify the license under which the code can be used or modified.
• Disclaimer: Add disclaimers for liability or warranty if necessary.

# © 2024 Samarth Amrute. All rights reserved.


Example…
Purpose: This comment clarifies ownership and provides the licensing
terms under which the code can be used.

# © 2024 Samarth Amrute. All rights reserved.

You might also like