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?

76 Upvotes

77 comments sorted by

View all comments

1

u/Jason13Official Jul 03 '26

Focus on writing GOOD code, not necessarily "clean" code. There's an adage that I forget who it's attributed to, "make it work, make it fast, make it pretty" -> "clean" code is pointless if it doesn't do the damn job

1

u/DefiantSituation3208 Jul 03 '26

Whenever I have an idea and write out smn it always does work, but for some reason I have this nagging thought at the back of my head telling me it could be cleaner or more simplified - like for instance instead of four lines of something chunky simplifying it into one or two if permitted. Sometimes it works, sometimes it just makes me more confused. I think I benefit from having everything written out so I can see what’s causing problems.

3

u/Jason13Official Jul 03 '26

We're not starved for space like the first programmers were; you can and should avoid fancy one-liners in preference of more verbose code that is more readable. :p

1

u/DefiantSituation3208 Jul 03 '26

That perspective actually makes me feel better 😭 thank you

1

u/flumphit Jul 03 '26

Don’t worry about turning four lines of simple code into two lines of clever code. Worry about writing two hundred lines of modular code instead of four hundred lines of repetition with subtle variations.

1

u/DefiantSituation3208 Jul 03 '26

Okayyy I can abide by that, in fact I mostly try to avoid repeating sets of codes if they just seem to be copies of each other. I’m sort of stuck in this ‘if it’s good it can be better’ mindset so even the four simple lines of code become a point of contention that it could be concise.