-
Notifications
You must be signed in to change notification settings - Fork 4
Clean Code Book
Is a book that outlines the principles and practices of writing clean, maintainable, and efficient code. The book emphasizes the importance of code readability, simplicity, and organization, and provides practical examples and case studies to illustrate its points.
The book is divided into three parts
- The Principles of Clean Code In the first part, Uncle Bob introduces the fundamental principles of clean code, such as keeping code concise and focused, naming functions and variables clearly, and using comments and documentation judiciously. He also stresses the importance of testing and refactoring code to ensure it stays clean and easy to maintain over time.
- The Practices of Clean Code In the second part, Uncle Bob provides practical advice on how to put these principles into practice. He discusses topics such as code formatting, error handling, and concurrency, and provides detailed examples of how to write clean code in various programming languages, including Python, Java, and C++. He also discusses tools and techniques for testing code, including unit testing, integration testing, and acceptance testing.
- Case Studies In the final part, Uncle Bob presents several case studies that illustrate how the principles and practices of clean code can be applied in real-world scenarios. These case studies cover a range of programming languages and domains, including web development, game programming, and financial applications.
Overall, "Clean Code" is an essential read for any programmer or software developer who wants to improve their coding skills and write code that is clean, efficient, and easy to maintain. The book is well-written, practical, and full of useful examples and advice, and is highly recommended for anyone who wants to write better code.
The first part of "Clean Code" by Robert Cecil Martin covers the principles of clean code. Here are some of the important points from this section:
- Naming conventions: Names of classes, functions, and variables should be descriptive and clear. Avoid using vague or generic names like
data
orresult
. Instead, use names that accurately reflect the purpose of the code. For example, instead of usingdata
as a variable name, useuser_data
.
# Poor naming example
d = {'a': 1, 'b': 2}
for key in d:
print(key)
# Good naming example
user_data = {'name': 'John', 'age': 30}
for field_name in user_data:
print(field_name)
- Functions: Functions should be small, do one thing, and do it well. They should have a clear input/output contract and should not have any side effects. The name of the function should also accurately reflect what the function does.
# Poor function example
def process_data(data):
for item in data:
# do something
# Good function example
def calculate_average(numbers):
total = sum(numbers)
return total / len(numbers)
- Comments: Comments should be used sparingly and should only be used to clarify complex or confusing code. Avoid using comments to explain what the code is doing; instead, use clear and descriptive variable/function names.
# Poor comment example
# This code calculates the average of a list of numbers
def average(numbers):
# do something
# Good comment example
def calculate_average(numbers):
# Calculate the average of a list of numbers
total = sum(numbers)
return total / len(numbers)
- Formatting: Code should be formatted consistently, using a consistent style for indentation, spacing, and line breaks. This makes the code easier to read and understand.
# Poor formatting example
def some_function():
for item in some_list:
if item > 5:
print(item)
# Good formatting example
def some_function():
for item in some_list:
if item > 5:
print(item)
- Testing: Code should be thoroughly tested to ensure it is correct and functions as intended. This includes writing unit tests for individual functions and integration tests for the system as a whole.
# Poor testing example
def calculate_average(numbers):
total = sum(numbers)
return total / len(numbers)
# Good testing example
def test_calculate_average():
assert calculate_average([1, 2, 3]) == 2.0
assert calculate_average([0, 0, 0]) == 0.0
assert calculate_average([-1, 1]) == 0.0
The second part of "Clean Code" focuses on principles and practices that can help make code more maintainable, including functions, comments, and error handling. Here are some of the key points:
- Functions should be small and do one thing: Functions that do more than one thing can be hard to understand and maintain. A good rule of thumb is to make sure that each function is no longer than a page and that it has a clear, single responsibility.
Example in Python:
# Bad example: function does multiple things
def process_data(data):
# manipulate data
...
# save data to file
...
# send email
...
# Good example: function does one thing
def manipulate_data(data):
# manipulate data
...
return manipulated_data
- Functions should have descriptive names: The name of a function should describe what it does. A reader should be able to understand what a function does just by looking at its name.
Example in Python:
# Bad example: unclear function name
def foo(a, b):
...
# Good example: descriptive function name
def calculate_sum(a, b):
...
- Comments should be used sparingly and should only explain why, not what: Comments should only be used to explain why something is being done, not what is being done. The code should be clear enough to explain what is happening.
Example in Python:
# Bad example: unnecessary comment
def calculate_sum(a, b):
# add a and b together
return a + b
# Good example: helpful comment
def calculate_sum(a, b):
# we need to calculate the sum of a and b because...
return a + b
- Error handling should be centralized: Error handling code should be in one place, not scattered throughout the code. This makes it easier to maintain and update error handling logic.
Example in Python:
# Bad example: error handling scattered throughout the code
def process_data(data):
if len(data) == 0:
print("Error: empty data")
return
# more processing code
# Good example: centralized error handling
def process_data(data):
try:
if len(data) == 0:
raise ValueError("Empty data")
# more processing code
except ValueError as e:
print("Error:", str(e))
These are just a few of the principles and practices covered in the second part of "Clean Code." By following these guidelines, you can write code that is easier to understand and maintain, and that will be more valuable to your team and organization.
The third part of "Clean Code" by Robert C. Martin covers code formatting, error handling, and testing.
- Code Formatting: Consistent formatting can improve readability and reduce errors. Use an agreed-upon formatting style, such as PEP 8.
# Bad example
def sum(x,y):
return x+y
# Good example
def sum(x, y):
return x + y
- Error Handling: Error handling can make code more resilient and easier to debug. Handle errors at the appropriate level and provide informative error messages.
# Bad example
try:
value = int(input("Enter a number: "))
except:
value = 0
# Good example
try:
value = int(input("Enter a number: "))
except ValueError:
print("Invalid input, setting value to 0.")
value = 0
- Testing: Testing can ensure code works as intended and provide a safety net for making changes. Write tests that cover all possible scenarios and use a testing framework like
unittest
.
# Bad example
def sum(x, y):
return x + y
# No tests
# Good example
def sum(x, y):
return x + y
import unittest
class TestSum(unittest.TestCase):
def test_sum(self):
self.assertEqual(sum(1, 2), 3)
self.assertEqual(sum(0, 0), 0)
self.assertEqual(sum(-1, 1), 0)
if __name__ == '__main__':
unittest.main()
- Introduction
- Variables
- Data Types
- Numbers
- Casting
- Strings
- Booleans
- Operators
- Lists
- Tuple
- Sets
- Dictionaries
- Conditionals
- Loops
- Functions
- Lambda
- Classes
- Inheritance
- Iterators
- Multi‐Processing
- Multi‐Threading
- I/O Operations
- How can I check all the installed Python versions on Windows?
- Hello, world!
- Python literals
- Arithmetic operators and the hierarchy of priorities
- Variables
- Comments
- The input() function and string operators
Boolean values, conditional execution, loops, lists and list processing, logical and bitwise operations
- Comparison operators and conditional execution
- Loops
- [Logic and bit operations in Python]
- [Lists]
- [Sorting simple lists]
- [List processing]
- [Multidimensional arrays]
- Introduction
- Sorting Algorithms
- Search Algorithms
- Pattern-matching Algorithm
- Graph Algorithms
- Machine Learning Algorithms
- Encryption Algorithms
- Compression Algorithms
- Start a New Django Project
- Migration
- Start Server
- Requirements
- Other Commands
- Project Config
- Create Data Model
- Admin Panel
- Routing
- Views (Function Based)
- Views (Class Based)
- Django Template
- Model Managers and Querysets
- Form
- User model
- Authentification
- Send Email
- Flash messages
- Seed
- Organize Logic
- Django's Business Logic Services and Managers
- TestCase
- ASGI and WSGI
- Celery Framework
- Redis and Django
- Django Local Network Access
- Introduction
- API development
- API architecture
- lifecycle of APIs
- API Designing
- Implementing APIs
- Defining the API specification
- API Testing Tools
- API documentation
- API version
- REST APIs
- REST API URI naming rules
- Automated vs. Manual Testing
- Unit Tests vs. Integration Tests
- Choosing a Test Runner
- Writing Your First Test
- Executing Your First Test
- Testing for Django
- More Advanced Testing Scenarios
- Automating the Execution of Your Tests
- End-to-end
- Scenario
- Python Syntax
- Python OOP
- Python Developer position
- Python backend developer
- Clean Code
- Data Structures
- Algorithms
- Database
- PostgreSQL
- Redis
- Celery
- RabbitMQ
- Unit testing
- Web API
- REST API
- API documentation
- Django
- Django Advance
- Django ORM
- Django Models
- Django Views
- Django Rest Framework
- Django Rest Framework serializers
- Django Rest Framework views
- Django Rest Framework viewsets