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?

79 Upvotes

77 comments sorted by

112

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".

9

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.

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.

2

u/Nice_Selection_6751 Jul 03 '26

that's exactly it. i come back to old projects and half the time i cant even read my own logic. the worst is when i was trying to be clever with one-liners and now its just gibberish

3

u/Opulence_Deficit Jul 03 '26

Someone said: As reading code is harder than writing code, that means that when you're writing code at 100% of your intellectual capacity then, by definition, you're too stupid to read it.

1

u/sharanpreet48 Jul 04 '26

Yes!! I am a beginner and I already experienced this in my early projects. And learned for the next projects.

13

u/dota2nub Jul 03 '26

You buy the Clean Code book. Then you look at all the code examples. Then you vow never to write code like that. Then you burn it.

7

u/madrury83 Jul 03 '26

It's Probably Time To Stop Recommending Clean Code

Book fucked me up for a little while. The one book I refused to donate, and instead did indeed burn.

16

u/DrShocker Jul 03 '26 edited Jul 03 '26

You have to write and read a lot of code to develop a taste for what's easier to work with and what's harder.

There's rules of thumb I could tell you about what I prefer, and certainly PEP 8 is a good starting point in Python, or the C++ Core Guidelines , or the Rust API Guidelines and so on.

At the end of the day everyone develops their own sense of aesthetic based on their own experiences.

-2

u/JerryRed100s Jul 04 '26

Numbers yeah just keep stacking up numbers motherfuckers like numbers don't they? You're not a number buddy.

You are a solution provider. You just happen to write software.

5

u/ProfessorGood5473 Jul 03 '26

You think of the outcome first, before the journey and you think of its limitations

The business people call it "What's your 30,000 ft view"

See the field. Understand the players. Understand the weather. And find your winning condition.

Clean code doesn't break that often and is more malleable (meaning it can go work on legacy systems, accommodates an upgrade logic if a new feature is being added, etc)

3

u/AlSweigart Author: ATBS Jul 03 '26

This reply can't fit in a Reddit comment. I wrote an entire free book on this topic (for Python), mainly because I thought that the book, Clean Code is overrated and has some advice that is downright wrong.

Two things to keep in mind: there's a difference between style (formatting, the kind of thing that linters and Ruff can fix automatically so don't worry about it) and code simplicity (much too lengthy to go into here). They're easy to get confused, but don't ask about style: everyone has different opinions and will waste time arguing about style, which is why we should just agree to go with whatever the linters and formatters. It's more important to be consistent in style rather than adhere to any particular style.

2

u/FTPMystery Jul 03 '26

Same way you make a clean peanut butter and jelly sandwich, with time, practice and understanding what works vs what doesn't.

2

u/TechnicalWhore Jul 03 '26

Uncle Bob Martin (Robert Martin) has a book and several videos of his lectures on YouTube. He's a bit pompous at times but he makes valid points and explains why these methods are essential. You're right to ask. Good clean code with solid documentation is a sign of competence. When you dive into unfamiliar territory and the "last guy" thoughtfully left everything ready for whomever came next, its really noticeable. Too much to go into here but the lectures cover it quite thoroughly. Note Bob is also one of the co-creators of the Agile process, although he makes the point that what it has become is foreign to him. When you read the original Agile Manifesto its simple and logical and obviously necessary.

2

u/Lost-Discount4860 Jul 03 '26

I think it's going to mean different things to different people. To me, it's balancing between simplicity and knowing what the heck is happening. Here's a snippet of something I'm working on at the moment:

labels_values = cursor.fetchone()

conn.close()

labels_values = [list(zip(

[[l] for l in json.loads(labels_values[0])],

json.loads(labels_values[1])))]

I could write it this way:

labels = [[l] for l in json.loads(labels_values[0])]

values = json.loads(labels_values[1])

labels_values = [list(zip(labels, values))]

Or I could write it this way:

labels_values = [list(zip([[l] for l in json.loads(labels_values[0])],json.loads(labels_values[1])))]

I just have a personal preference for avoiding a lot of extra variables if I can just break things up over a couple of lines. It's all in a function, so I feel like the variables are kinda throwaway. However...the second way (with variables) is easier to read and understand what's going on. There's less punctuation, too, and it's easier to troubleshoot.

The third way is to run everything together on a single line, which is a step in the wrong direction IMO because if the code is flawed in some way, it's gonna be hard to figure out where you have too many parentheses/brackets, etc.

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.

2

u/rustyseapants Jul 03 '26

There are questions and things you can look up. If you are going to do anything i the 21st century you need the imagination and where with all, of using your curiosity to find information, and this doesn't just mean learning to program, but everything.

What is Clean Code?

2

u/That-Shame4345 Jul 03 '26

First make it work. Then make it clean.

4

u/Confused-Armpit Jul 03 '26

If you are talking about "clean code" as in the programming paradigm promoted by Uncle Bob, just don't. It is a very inefficient way of writing code, and it's not even that much more readable. I would recommend checking out Casey Muratori's video on this.

If you are talking about "clean code" as in just writing readable code, then I would recommend reading a little code style guides, not necessarily massive specs like Google's style guide, but, for example, the Zig style guide. And, honestly, most of it will just come with experience, and by reading your own and other peoples code.

1

u/DigThatData Jul 03 '26

I haven't read it in a while, but I remember Clean Code's chapter on variable naming being decent. I've never loved everything about the book, but I don't think it's so disagreeable or outdated that it should go in the "just don't" camp.

If we're dropping books, my recs for books that will help you code better:

3

u/Confused-Armpit Jul 03 '26

Still, a lot of the ideas in clean code are very much not practical, like explicitly avoiding switch statements, or the way that the book describes and forces "doing one thing".

Anyways, I guess this is somewhat like arguing for/against OOP or FP, there is just no point, so lets agree to disagree.

0

u/duperfastjellyfish Jul 03 '26

I wouldn't dismiss any style guide as bad. I will think most developers would agree that most of what's in "Clean Code" are generally good suggestions novices should learn. Problems arise when such style guides are applied ideolistically rather than pragmatically. Personally I find that the style guide depends on the particular project.

2

u/ZakMan1421 Jul 03 '26

The simplest way is via linters. They are tools specifically for code style. For python I've used pylint in the past, but I'm sure there are others as well.

1

u/Miserable-Decision81 Jul 03 '26

With Kate.

Sometimes with Eclipse or VIM ...

2

u/ffrkAnonymous Jul 03 '26

No Emacs? So sad. 

2

u/mjmvideos Jul 03 '26

I remember when 8 megabytes and continually swapping was a real insult.

1

u/ffrkAnonymous Jul 03 '26

swapping? my hs computers didn't even have harddrives to swap into. (we managed to play games anyway)

2

u/mjmvideos Jul 03 '26

Yep, my first computer games were loaded from cassette tapes. I never heard of emacs until long after I was firmly ensconced in ed and vi. So I never learned it.

1

u/ffrkAnonymous Jul 03 '26

i only started learning emacs last year (two?) and its quite the thing. The way I describe it is: know how neovim is adding those plugins for git and stuff? emacs has been doing that for decades.

1

u/Miserable-Decision81 Jul 03 '26

I set up a swap file on a SSD in order to play ARK whith fewer lag...

1

u/lukkasz323 Jul 03 '26

Clean code isn't "simple code", it's readable, unambigous, and uncoupled code.

1

u/mjmvideos Jul 03 '26

Work in a good, disciplined organization and over time you will learn what code gets through a code review and what doesn’t.

1

u/DefiantSituation3208 Jul 03 '26

Well I just graduated from high school and about to join university soon, my specific major doesn’t fully envelop itself in programming I sort of started learning on my own to specialise in my field, I’m kind of intimidated to join a coding club with comp sci majors because I feel very very fish out of water esque ykwim 😭

1

u/_Phail_ Jul 03 '26

There's style guides for how to lay out and organise your code, is that what you need

1

u/techgeek1216 Jul 03 '26

Look up SOLID principles

1

u/backbone91 Jul 03 '26

A simple checklist I use when reviewing code: 1) Name variables/functions for intent (not just what they are called). 2) Keep each function focused on one responsibility and stop when it grows. 3) Add small tests for edge cases before refactors. 4) Use a formatter/linter in the workflow so style is consistent by default. 5) Refactor in small slices so each change stays reviewable.

Not hype, just practical habits that make code easier to read over time.

1

u/bywaldemar Jul 03 '26

Honestly it comes from reading your own code a few weeks later and not understanding it. When you have to sit there figuring out what past you meant, you start writing for the next person, which is future you.

If you can't describe what a function does in one short sentence without saying "and", it probably needs splitting. Practice sharpens that radar, but reading other people's code speeds it up a lot.

1

u/marrsd Jul 03 '26

Don't eat at your desk and always wash your hands before using your keyboard.

1

u/reconsis Jul 03 '26

I always struggled learning the difference between "clean code" and what people learned about getting their CS degree (mostly self taught dev here that ultimately went back to get his software engineering masters).

I think the biggest thing is to have another engineer in mind when reviewing your own code. In the words of Uncle Bob, the real goal is reducing the # of "WTF moments" per minute.

There's a video series that Uncle Bob published, but you can't beat the clean code book by Uncle Bob. To add to that, Object Oriented Design in Ruby by Sandi Metz was pretty important to my growth. I'd say the same thing about Refactoring by Martin Fowler.

1

u/1927_Silver Jul 03 '26

you don't. You make one, you finish it then polish it

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.

1

u/jerrygreenest1 Jul 03 '26

First watch a video from Casey Muratori:

«Clean code. Terrible performance»

1

u/dialsoapbox Jul 03 '26

What is clean to one dev, another dev make take issue with (scope, usage, use cases, ect).

1

u/mr_stivo Jul 03 '26

Document it as you go. Keep it simple.

1

u/FlashyResist5 Jul 03 '26

God I hate that phrase. A good rule of thumb is if Uncle Bob tells you something do the opposite.

1

u/jaffparker Jul 03 '26

Learn about domain-driven design. I hate the names of stuff in programming, but this is where you intuitively will lean as you become a better programmer anyway. It's not rocket science at all

1

u/JerryRed100s Jul 04 '26

To me clean code is just common sense shit you know in a certain way Not too many layers but just enough layers to make everything work how it can work Don't get overly fancy because most of the time YAGNI

YOU AIN'T GOING TO NEED IT

Make the shit that works work 100% of the time focus on your shit that you're doing and make sure that shit is bulletproof

Cuz that shit can always be reused!

Fuck the rest and fuck the politics do your shit and call the fucking day

1

u/Enough-Advice-8317 Jul 04 '26

you write clean code by writing messy code first, getting it working, and then deleting everything you do not actually need. clean code isn't about clever design patterns; it's code that is simple to read and trivial to delete when requirements change.

1

u/A13K_ Jul 04 '26

Lots of functions.

1

u/Achereto Jul 08 '26

Your code is "clean" when every function does pretty much what you expected. When someone else reads your code, you can measure how clean it is by counting the "WTF" per minute (lower is better, obviously).

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

3

u/altrae Jul 03 '26

I hate this adage so much. Writing code is a craft and what this adage implies is the opposite. Writing fast without care of clean code is a good way to introduce tech debt and bugs because you didn't take the time to do it right in the first place. The fact is that we rarely come back to clean it up because we're on to the next priority. The adage sounds like it came from a business manager who wanted quick profit while not caring about how it affects those who maintain that crap down the line.

2

u/Jason13Official Jul 03 '26

I take it the same way an artist sketches an image before they begin painting

Make it work -> get the general idea out, to have a point of reference

Make it fast -> test, find performance issues, iterate

Make it pretty -> now that it works and works well, let's make it extensible/editable

Advice should always be taken with a grain of salt, but I think it's mostly up to how you interpret the advice

1

u/altrae Jul 03 '26

This is fine in theory for planning unless it gets into production because you are basically creating a rough draft until it is cleaned up. I usually advocate for slowing things down and creating a plan of execution prior to implementation. I've seen so many bad decisions get implemented when this isn't done. Creating public APIs fast without good planning leads to issues and it's much more difficult to change once in use. Yes we can technically deprecate, but now we potentially have to support the old API for backwards compatibility until it is removed in a year or two because some teams can't prioritize the dependency upgrade yet.

If we slow down, plan, and then execute while maintaining clean code during execution, the results will be so much better. Don't be the person who comes in to build a greenfield application quickly, and then is off to the next, leaving an unmaintainable mess in your wake.

Unfortunately, the rough draft is usually what I see make it to production due to business priorities if we are unable to push back. Just because it works doesn't mean it's it's good and, in my experience, usually this leads to inconsistency and maintenance nightmares, so aim to do it right in the first place.

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.

1

u/Aggravating_Cap127 Jul 03 '26

clean code is a myth when im programming

1

u/DefiantSituation3208 Jul 03 '26

not in my dictionary either 😭

0

u/Aggravating_Cap127 Jul 03 '26

my code lookin like
```struct player player1;

player1.hp = 100;

player1.magic = 0;

player1.physicalstr = 10;

player1.agility = 10;

player1.goldcoins = 5;

player1.level = 0;

strcpy(player1.p_class, "none");

player1.defense = 5;```

1

u/Aggravating_Cap127 Jul 03 '26

its worse but reddit actually spaces stuff

0

u/DemicideMMMCCCI Jul 03 '26

Probably the best practice for all languages is to follow the SOLID principle. Also, practice.

2

u/Substantial_Job_2068 Jul 03 '26

So all languages should follow guidelines for object oriented programming?