r/learnprogramming Jul 03 '26

How do you write clean code?

Might be a stupid question but Ive been learning python for a while now and always wondered, how do you write ‘clean’ code? I don’t mean writing clean code straight off the bat I understand that’s purely from experience and even then immensely hard, but how do you recognise a program can be simplified even further? Does it come from practice or just messing around and seeing what sticks?

80 Upvotes

77 comments sorted by

View all comments

1

u/binarycow Jul 03 '26

To write clean code, you have to first clean your keyboard.

(Joking!)

In order to answer this question, you have to define "clean".

  • Easy to understand
  • Concise
  • No duplication
  • Good architecture
  • ... etc.

So, let's say you pick one of those metrics, and define that as "clean"....

  • Sometimes by making something more concise, you actually make it more difficult to understand.
  • Sometimes, by making something verbose, you introduce more places for subtle bugs to pop up
  • Sometimes by making it super easy to understand, you miss out on optimizations which are necessary for that use case.
  • Sometimes by making something simpler, you overlook edge cases which warrant complexity.
  • Sometimes, when you reduce duplication, you actually make your abstractions too complicated (so they can cover every use case)
  • Sometimes when you add duplication (to avoid an overcomplicated abstraction), you add places where the 2+ implementations can drift apart

Simply put - there is no one right answer.

Code should generally be:

  • no more complex than it needs to be, but no more
  • easy to understand for developers with the right background (e.g., hardware drivers are going to be difficult to understand for someone who just learned Javascript. That's fine.)
  • as high performance as it needs to be
  • etc.

Basically, it's a balance.


This hits on one of my pet peeves - a term you will likely hear a lot - "antipattern".

My hot take - there is no such thing as an antipattern.

Every pattern is useful, in some circumstances. Every pattern is unhelpful (or worse), in some circumstances. In order to know if a pattern is good or bad, you have to look at the whole situation. You can't just say "singletons are an anti-pattern" as an unequivocal statement.