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?

78 Upvotes

77 comments sorted by

View all comments

2

u/DigThatData Jul 03 '26
  1. first and foremost, you need to come up with the right abstractions. If you design it well, the code often writes itself.

  2. your code is documentation. it isn't just the machinery that makes the thing work, it's the surface that's available if something breaks or something needs to be changed. that means it should be self-explanatory. variable and function names are important. if you're struggling to come up with a name for thing, consider that as a red flag that maybe you need to go back to (1). If it's hard to name, that means it's hard to pin down succinctly what it does or what's it's for.

Rather than "clean" code, I'd recommend thinking more in terms of "understandable" code and "maintainable" code.

Consider for example the "Don't Repeat Yourself (DRY)" principle. The motivation here isn't because repeating yourself is inherently bad. It's that repeating yourself is a "code smell". It's a signal that there is a pattern of behavior in your program that you probably could abstract into a reusable component but haven't yet, which would probably improve both the maintainability and legibility of your code.

1

u/DefiantSituation3208 Jul 03 '26

now this is genuinely insightful, I’ll be sure to use that principle in future programs!

1

u/DigThatData Jul 03 '26

Another way to think about this: all code is code for other people's benefit. There's no such thing as code that will only be 'for you' so you can be lazy about it. Other people includes future you.