Writing Clean Code
How Clean Are You Writing ?
Clean code means writing code that you and others can easily read and understand. It follows principles and practices that enhance readability, minimize complexity, and promote efficient collaboration among developers.
Writing free code means writing code that is easy to maintain, debug, and modify.
Naming
You need to understand what a method, class, enumeration, variable, or property does just by reading its name.
Singular nouns for single values
If you give a collection a singular name, you and others may not realize that it is a collection without variable declarations.
Plural nouns for the collection of values.
If you give a primative variable a singular name, you and others may not realize it is a primative variable without a variable declaration.
Avoid single letters and abbreviations.
Just by reading the name, everyone needs to understand. Defining a variable named x
and y
doesn’t explain what a variable is for (Except for Coordinates.)
Give a not too long but meaningful name
numberOfStudentsInClassroom = 42
numberStudents = 42
numberOfStudentsInClassroom
is too long to read, you can use numberStudents
that have the same meaning.
text = "Writing clean code"
for w in text.split():
print(w)
In this w
stands for word,” but it isn’t so meaningful; instead, we can write a code like this.
text = "Writing clean code"
for word in text.split():
print(word)
Being specific makes it easier to read.
Distinguish between abbreviations
class HTTPAPI:
# More code...
As you can see, HTTPAPI
is particularly difficult to read, especially for people who don’t understand what they are. Instead, separating two words with a comma_
, such as HTTP_API
, improves readability.
class HTTP_API:
# More code...
Naming Constants
- Languages like Go and C# capitalize characters for a constant variable.
- In languages such as Python, Java, C++, JavaScript, Ruby, the first letter of each character is capitalized and separated by a “_”.
const int MaxValue = 100; # C#
const int MAX_VALUE = 100; # C++
const MaxValue = 100; # Go, JavaScript
MAX_VALUE = 100 # Python, Ruby
final int MAX_VALUE = 100; # Java
Naming Enum Members
The name of the enum members must be meaningful with the name of the enum.
# Bad
enum Color {
OPTION1,
OPTION2,
OPTION3
}
# Good
enum Color {
RED,
GREEN,
BLUE
}
New Lines After Curly Braces
You have two options for new lines after curly braces:
if (value)
{
...
}
else
{
...
}
if (value) {
...
}
else {
...
}
But do not confuse the two. It makes the code harder to read.
if (value) {
...
}
else
{
...
}
Vertical Whitespace
- improves top-to-bottom readability
- Used to group chunks of code
Between Function Definitions
Add a vertical whitespace (a new line) before function definitions.
def max():
pass
def min():
pass
// start code here
After Function Definitions
Add a vertical whitespace (a new line) before function definitions.
class Person:
pass
// start code here
Before Comment Lines
Add a new line before comment lines
// add a new line before a comment line
a = 1
Horizontal Whitespace
- Improves left-to-right readability
Space After Every Comma
print("Hello","World") # bad
print("Hello", "World") # good
Space Before and After Comments
# Python Comment
// C#, Java, JavaScript comment
Space Before and After Operations (+, -, /, *, =)
number1 = 10
number2 = 11
Number 3 = number 1 + number2
Comments
- Only read by humans and interpreted by a compiler or interpreter.
- Based on “why” question
- Do not answer the what question (code tells what “what” is code for); answer the “why” question.
Bad Comments
# Hello World to computer
print("Hello World")
# Multiplying number
number1 = 10
number 2 = 10 * 10
# Good Comments
Increase the retry count to handle intermittent network errors
retry_count += 1
Boolean Logic
Instead of long boolean logic, you can replace boolean logic with function. In this way, if you look at it later or someone else looks at it, it will be easier to understand what boolean logic does.
Check if the user is eligible for a discount based on their membership status and purchase amount
if user.membership == Membership.GOLD and purchase_amount >= 100) or (user.membership == Membership.SILVER and purchase_amount >= 200):
apply_discount()
else:
display_regular_price()
def is_eligible_for_discount(user_membership, purchase_amount):
if user_membership == Membership.GOLD and purchase_amount >= 100:
return True
elif user_membership == Membership.SILVER and purchase_amount >= 200:
return True
else:
return False
# Usage
if is_eligible_for_discount(user.membership, purchase_amount):
apply_discount()
else:
display_regular_price()
Conclusion
As a result, writing clean code allows us and others to understand and read the code without much effort, just by typing the correct names of the functions, classes, properties, and enums we use. You can reach them by using comment lines, new lines, and spaces correctly.