Clean code

How to write clean code?

Writing clean code is a lot like painting a picture. Most of us know when a picture is painted well or badly. But being able to recognize good art from bad does not mean that we know how to paint. So too being able to recognize clean code from dirty code does not mean that we know how to write clean code!
A programmer who writes clean code is an artist who can take a blank screen through a series of transformations until it is an elegantly coded system.
There are two parts to learning clean code: knowledge and work:
  • You must have knowledge of the principles, patterns, practices, and experience that a craftsman knows.
  • You also have to grind those skills through hard work and practice.
Clean code consists of:
  • Your developer mindset (empathy, craftsmanship, growth mindset, design thinking)
  • Your coding conventions (naming things, refactoring, testing, etc)
  • Your skills & knowledge (of patterns, principles, and how to avoid code smells and anti-patterns)

Follow clean code principles

The most important principles to keep our code clean:
  • SOLID*: Single Responsibility Principle (SRP), Open-Closed Principle (OCP), Liskov substitution principle (LSP), Interface Segregation Principle (ISP), and Dependency Inversion Principle (DIP).
    • Design principles, this is a topic in itself but mastering the SRP will already help us in a tremendous way.
  • KISS (Keep It Simple Stupid):
    • Simplicity should be a key goal in design, and unnecessary complexity should be avoided.
    • The question to ask when you're writing code is "can this be written in a simpler way?”
  • DRY (Don't Repeat Yourself):
    • Each piece of knowledge must have a unique, unambiguous, authoritative representation in a system.
    • When the DRY principle is applied successfully, a modification of any single element of a system does not require a change in other logically unrelated elements.
  • YAGNI (You Aren't Gonna Need It):
    • A developer should not add functionality unless deemed necessary.
    • Always implement things when you actually need them, never when you just foresee that you need them.
  • Boy-scout rule: Always leave the code better than you found it.
  • Don't reinvent the wheel: There are already tons of libraries that can help solve our problems so we don't have to do it again.
  • Design Patterns: There are tons of design patterns out there, and some people already resolved our problem.
  • Coding Standards/Conventions: So we don't end up having different codes with different coding styles among our team.

Create the habits of clean coding