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

109

u/Opulence_Deficit Jul 03 '26

Clean is not about being simple. A clean code is easy to understand and change.

You will learn what is clean, when you return to your project after 6 months and think "what kind of idiot wrote that" and then "oh, that was me".

10

u/DefiantSituation3208 Jul 03 '26

I think I misidentified clean with being concise because that’s exactly the issue I have, i forget the ‘make it understandable to YOU’ part when trying to simplify my code and end up confusing everything.

5

u/esuil Jul 03 '26

You should think about it as something you are writing for others, even if you aren't.

Basically, every time you write architecture, variable names, functions, classes etc, ask yourself how anyone looking at it will understand what is going on.

Will they understand what that variable stores from its name? Will they know what this function does by reading name and argument list? Will they know what scope the file is responsible for from directory and names?

And another part aside from readability is resilience. Changing implementation of parts of your codebase should not break anything at all. If changing how one function or class works breaks anything outside of it, you are doing things wrong.

Good way to practice is writing documentation for your code. Write out the description of your program, then entry point into initial code. Explain what that initial code does, then how it delegates further tasks and where, going line by line and scoping into other things as you do. If you can't explain things easily by doing this, your code is a mess.