DEV Community

Zahoor Ahmed shah
Zahoor Ahmed shah

Posted on

10 Best Practices for Writing Clean Code -with simple examples

10 Best Practices for Writing Clean Code -with simple examples
As an experienced software developer, I’ve come to realize that writing clean code is crucial for the long-term maintainability and scalability of software projects. Clean code is easy to read, understand, and modify, which makes it easier for other developers to collaborate and maintain the codebase. In this article, I’ll share some best practices for writing clean code with examples in the Ruby language.
Photo by Emile Perron on Unsplash<br>
Photo by Emile Perron on Unsplash

1. Keep it Simple.

The first rule of writing clean code is to keep it simple. Avoid using complex code or obscure language features that are hard to understand. Use simple, clear names for variables, functions, and classes. Here’s an example:

# Bad code
def process_user_data(user_data)
  user_data.each do |k, v|
    if k == :name && v.length > 10
      puts "Name is too long"
    end
  end
end

# Good code
def process_user_data(user)
  if user.name.length > 10
    puts "Name is too long"
  end
end
Enter fullscreen mode Exit fullscreen mode

In the bad code example, the function is unnecessarily complex, using a loop to process user data. In the good code example, we simplify the function by passing in a user object and using a simple conditional statement to check the length of the name.

2. Write Readable Code.

Readable code is easy to understand. Use consistent formatting, indentation, and spacing. Write comments to explain what your code is doing. Here’s an example:

# Bad code
def multiply(x, y)
x * y
end
# Good code
# Multiplies two numbers
def multiply(x, y)
  x * y
end
Enter fullscreen mode Exit fullscreen mode

In the bad code example, there are no comments or whitespace, making the function hard to read. In the good code example, we use a comment to explain what the function does and whitespace to separate different parts of the code.

3. Use Meaningful Variable Names.

Choose variable names that are meaningful and descriptive. Use names that describe what the variable represents. Here’s an example:

# Bad code
a = 10
b = 20
c = a + b

# Good code
first_number = 10
second_number = 20
sum = first_number + second_number
Enter fullscreen mode Exit fullscreen mode

In the bad code example, the variables are named with single letters, which doesn’t provide any context. In the good code example, we use descriptive variable names that make it clear what the code is doing.

4. Use Consistent Naming Conventions.

Use a consistent naming convention throughout your code. This will make it easier to read and understand. Here’s an example:

# Bad code
def get_users_data
end

def getUserData
end

# Good code
def get_users_data
end

def get_user_data
end
Enter fullscreen mode Exit fullscreen mode

In the bad code example, we have two functions with different naming conventions, making the code inconsistent and harder to read. In the good code example, we use the same naming convention for both functions, making the code more consistent and easier to read.

5. Avoid Long Functions.

Write functions that are short and do one thing. This will make it easier to understand what the function is doing and to debug it if necessary. Here’s an example:

# Bad code
def process_user_data(user_data)
  # do a lot of processing here
end

# Good code
def validate_user_data(user_data)
  # validate the user data here
end

def process_user_data(user_data)
  # process the user data here
end
Enter fullscreen mode Exit fullscreen mode

In the bad code example, we have a function that does a lot of processing, making it harder to understand and debug. In the good code example, we break up the function into two smaller functions that do one thing each — one for validating user data and the other for processing user data. This makes it easier to understand and maintain the code.

6. Use White Space Effectively.

Use white space to separate different parts of your code. This will make it easier to read and understand. Here’s an example:

# Bad code
def process_user_data(user_data)
if user_data[:name].length > 10
puts "Name is too long"
end
end

# Good code
def process_user_data(user_data)
  if user_data[:name].length > 10
    puts "Name is too long"
  end
end
Enter fullscreen mode Exit fullscreen mode

In the bad code example, there is no white space between the function name and the opening parenthesis, making it harder to read. In the good code example, we use white space to separate different parts of the code, making it easier to read and understand.

7. Write Self-Documenting Code.

Write code that is self-documenting. Use descriptive names for variables, functions, and classes. Write code that is easy to read and understand without comments. Here’s an example:

# Bad code
def f(a, b)
  # do some calculations here
  return result
end

# Good code
def calculate_sum(a, b)
  # calculate the sum of two numbers
  return a + b
end
Enter fullscreen mode Exit fullscreen mode

In the bad code example, the function name and variable names are not descriptive, making it harder to understand what the code is doing. In the good code example, we use descriptive names for the function and variables and add a comment to explain what the function does.

8. Use Version Control.

Use version control software such as Git to manage your code. This will make it easier to track changes and collaborate with other developers. Here’s an example:

$ git commit -m "Added new feature to user profile page"

Enter fullscreen mode Exit fullscreen mode

By using Git, we can easily track changes to our code and collaborate with other developers. This makes it easier to maintain the codebase and keep it clean.

9. Test Your Code.

Write unit tests to test your code. This will help to ensure that your code is correct and that it works as expected. Here’s an example:

# Bad code
def calculate_sum(a, b)
  a + b
end

# Good code
def calculate_sum(a, b)
  if a.nil? || b.nil?
    raise ArgumentError.new("Both arguments are required")
  end
  a + b
end
Enter fullscreen mode Exit fullscreen mode

In the bad code example, there are no tests to ensure that the function works as expected. In the good code example, we add a test to ensure that the function throws an error when either argument is nil.

10. Refactor Your Code.

Refactor your code regularly to keep it clean and maintainable. This will make it easier to add new features and fix bugs. Here’s an example:

# Bad code
def calculate_sum(a, b)
  if a.nil? || b.nil?
    return 0
  else
    return a + b
  end
end

# Good code
def calculate_sum(a, b)
  return a.to_i + b.to_i
end
Enter fullscreen mode Exit fullscreen mode

In the bad code example, we have an unnecessary conditional statement, making the function harder to read. In the good code example, we simplify the function by converting the arguments to integers before adding them.

Conclusion

Writing clean code is essential for the long-term maintainability and scalability of software projects. By following these best practices, you can write clean, easy-to-read

Top comments (0)