Writing Clean Code

Jacob Gjørva
3 min readMar 28, 2023

--

Clean code is the hallmark of a skilled developer. While coding practices such as following style guides, using meaningful names, and writing DRY code are widely known, there are other not-so-obvious ways to elevate the quality of your code. In this article, we will explore some unconventional tips for writing clean code that all developers can benefit from.

Embrace the Power of Constraints

Limiting yourself to a specific set of tools or frameworks can help you become more creative in solving problems. Constraints can simplify your code and make it easier to maintain. For example, restrict yourself to using only standard libraries for a project, or challenge yourself to write a solution in a certain number of lines. By doing this, you’ll learn to focus on the essentials and ultimately create cleaner, more efficient code.

See the example below:

# Using only standard libraries
import random

def generate_random_numbers(limit, count):
return [random.randint(1, limit) for _ in range(count)]

print(generate_random_numbers(100, 5))

Treat Your Code Like a Story

Every piece of code has a story to tell. By treating your code as a narrative, you can better understand its flow and structure. Start by creating a high-level outline of your code’s story, and use comments to explain the “plot” and “characters.” This approach will help you and your teammates visualize the code’s purpose and make it easier to maintain and refactor.

# The story of a function that checks if a number is prime

def is_prime(number):
"""Check if a given number is prime."""
if number <= 1:
return False
for i in range(2, number):
# The 'antagonist': a divisor that proves the number is not prime
if number % i == 0:
return False
# The 'resolution': the number is prime
return True

print(is_prime(5))

Master the Art of Abstraction

Abstraction is the process of simplifying complex systems by breaking them down into smaller, more manageable components. Mastering this art can lead to cleaner, more modular code. To practice abstraction, try breaking down a complex problem into smaller parts, and then create functions or classes to handle each part. This will help you maintain a clean separation of concerns, making your code easier to understand and maintain.

# Example of abstraction with classes
class Animal:
def speak(self):
raise NotImplementedError()

class Dog(Animal):
def speak(self):
return "Woof!"

class Cat(Animal):
def speak(self):
return "Meow!"

animals = [Dog(), Cat()]

for animal in animals:
print(animal.speak())

Embrace Test-Driven Development (TDD)

Test-driven development (TDD) is an approach to software development where you write tests for your code before writing the code itself. By adopting TDD, you can ensure that your code is clean, well-structured, and does exactly what it’s intended to do. Start by writing a test for a specific functionality, then write the code to pass the test. This will help you focus on writing only the necessary code and avoid over-engineering.

import unittest

def add(a, b):
return a + b

class TestAddition(unittest.TestCase):
def test_addition(self):
self.assertEqual(add(1, 2), 3)
self.assertEqual(add(-1, 1), 0)
self.assertEqual(add(0, 0), 0)

if __name__ == '__main__':
unittest.main()

Reflect on Your Code Regularly

Continuously evaluating and reflecting on your code can lead to significant improvements over time. Set aside time to review your work, and identify areas that could be improved or simplified. Use this as an opportunity to learn from your mistakes and refine your coding skills.

# Initial implementation
def old_sum_of_squares(numbers):
result = 0
for number in numbers:
square = number * number
result += square
return result

# After reflection and optimization
def new_sum_of_squares(numbers):
return sum(number * number for number in numbers)

print(old_sum_of_squares([1, 2, 3, 4]))
print(new_sum_of_squares([1, 2, 3, 4]))

Conclusion

Writing clean code is a continuous journey that requires constant learning and improvement. By embracing constraints, treating your code like a story, mastering abstraction, adopting TDD, and reflecting on your work, you can elevate your coding skills to new heights. Remember, clean code isn’t just about making your code look pretty — it’s about making it more efficient, maintainable, and easier to understand for you and your fellow developers.

Thanks for reading :)

--

--

Jacob Gjørva
0 Followers

My passion lies in breaking down complex concepts into easy-to-understand articles, making the world of science accessible to everyone.