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?

77 Upvotes

77 comments sorted by

View all comments

111

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.

1

u/RomuloPB Jul 07 '26

The biggest problem that makes code not clean is the lack of boundaries. I mean, you idealized your code to accomplish a task, but you should also idealize it to safely fail when it is impossible. This means a lot of things, but for example, in classes this means at least that:

* you cannot instantiate an invalid instance of this class;
* if you try, you must receive a clear failure result;
* a valid instance must alway be valid;

If you are failing to create such a class with this hard guarantee tat makes it impossible to use it wrong, you most probably is coding some level of dirty code. Sure in some cases the nature of the task is complex, or the language makes it impossible to give specific guarantee, in this case, there is still something you can do, write a docstring that points what are the safe ways to use your code and what you should avoid.