Clean Coding Principles

Joseph Salu
2 min readJun 5, 2021

Technical debt is depressing. Writing sloppy codes injects technical debts into our projects. Developers should write codes like Authors. Clean code is focused on humans, so you must write codes such that your intents are clear to human readers.

“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” (Martin Fowler)

“Programming is the art of telling another human what one wants computer to do.” (Donald Knuth)

  1. Don’t Repeat yourself (DRY). Express a logic once in your code
  2. Keep It Simple Stupid (KISS). Ask yourself, “can this code be written in a simpler way ?”
  3. Single responsibility. Each function should only do one thing
  4. You aren’t gonna need it (YAGNI). Do not add unnecessary codes you think you might need. Wait till you need it
  5. Use proper names for variables, functions and classes to describe intent. Avoid using abbreviations or generic names. A function or class should do exactly what the name says
  6. Initialise variables just-in-time (Mayfly variables)
  7. Use positive conditionals. Do not be anti-negative
  8. Use ternary operators instead of simple if else statements. However, avoid using nested ternaries
  9. Reduce if/else statements. Most often, we don’t need an else statement, as we can just use return inside the ‘if’ statement
  10. Avoid complex conditionals, instead, use intermediate variables or encapsulate via function
  11. Use polymorphism rather than proliferating codes with same switch statements
  12. Assign and compare booleans implicitly
  13. Prefer declarative over imperative. Use tools like Linq to filter over data structures
  14. Avoid using magic numbers or magic strings, instead, use constants or enums where necessary.
  15. Avoid unnecessary comments. Codes should self-documenting
  16. Avoid excessive indentations in your functions
  17. Codes should be TED compliant. Your functions must be Terse (Not too wordy), Expressive and Do one thing well
  18. Switch to table driven methods instead of hard-coding different values e.g. pricing options, tax rates
  19. High number of parameters make codes unreadable. If there are too many parameters, it may be violating single responsibilities. Max 3 parameters
  20. Avoid having long functions. Scrolling should not be required. Functions should not be longer than 20 lines
  21. Return early, Fail fast and Fail loud. Have Guard clauses. If you can’t handle exception throw it, do not just leave it
  22. Methods in a class should be related. Otherwise split up classes with low cohesion
  23. In general, reduce the Cyclomatic complexity of your codes

--

--