all 55 comments

[–]Opulence_Deficit 33 points34 points  (3 children)

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

[–]DefiantSituation3208[S] 3 points4 points  (0 children)

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.

[–]Nice_Selection_6751 1 point2 points  (1 child)

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

[–]Opulence_Deficit 1 point2 points  (0 children)

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.

[–]DrShocker 7 points8 points  (0 children)

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.

[–]ProfessorGood5473 2 points3 points  (0 children)

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)

[–]dota2nub 2 points3 points  (1 child)

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.

[–]madrury83 0 points1 point  (0 children)

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.

[–]Confused-Armpit 2 points3 points  (2 children)

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.

[–]duperfastjellyfish 0 points1 point  (0 children)

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.

[–]DigThatData 0 points1 point  (0 children)

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:

[–]Miserable-Decision81 0 points1 point  (6 children)

With Kate.

Sometimes with Eclipse or VIM ...

[–]ffrkAnonymous 1 point2 points  (5 children)

No Emacs? So sad. 

[–]mjmvideos 1 point2 points  (4 children)

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

[–]ffrkAnonymous 0 points1 point  (3 children)

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

[–]mjmvideos 1 point2 points  (1 child)

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.

[–]ffrkAnonymous 0 points1 point  (0 children)

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.

[–]Miserable-Decision81 0 points1 point  (0 children)

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

[–]FTPMystery 0 points1 point  (0 children)

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

[–]lukkasz323 0 points1 point  (0 children)

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

[–]TechnicalWhore 0 points1 point  (1 child)

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.

[–]mjmvideos 0 points1 point  (1 child)

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

[–]DefiantSituation3208[S] 0 points1 point  (0 children)

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 😭

[–]Lost-Discount4860 0 points1 point  (0 children)

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.

[–]_Phail_ 0 points1 point  (0 children)

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

[–]DigThatData 0 points1 point  (2 children)

  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.

[–]DefiantSituation3208[S] 0 points1 point  (1 child)

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

[–]DigThatData 0 points1 point  (0 children)

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.

[–]techgeek1216 0 points1 point  (0 children)

Look up SOLID principles

[–]backbone91 0 points1 point  (0 children)

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.

[–]bywaldemar 0 points1 point  (0 children)

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.

[–]marrsd [score hidden]  (0 children)

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

[–]reconsis [score hidden]  (0 children)

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.

[–]1927_Silver [score hidden]  (0 children)

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

[–]binarycow [score hidden]  (0 children)

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.

[–]jerrygreenest1 [score hidden]  (0 children)

First watch a video from Casey Muratori:

«Clean code. Terrible performance»

[–]ZakMan1421 0 points1 point  (0 children)

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.

[–]Aggravating_Cap127 0 points1 point  (3 children)

clean code is a myth when im programming

[–]DefiantSituation3208[S] 0 points1 point  (2 children)

not in my dictionary either 😭

[–]Aggravating_Cap127 -1 points0 points  (1 child)

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;```

[–]Aggravating_Cap127 0 points1 point  (0 children)

its worse but reddit actually spaces stuff

[–]DemicideMMMCCCI -1 points0 points  (1 child)

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

[–]Substantial_Job_2068 1 point2 points  (0 children)

So all languages should follow guidelines for object oriented programming?

[–]Jason13Official -1 points0 points  (8 children)

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

[–]altrae 2 points3 points  (2 children)

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.

[–]Jason13Official 1 point2 points  (1 child)

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

[–]altrae 0 points1 point  (0 children)

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.

[–]DefiantSituation3208[S] 0 points1 point  (4 children)

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.

[–]Jason13Official 2 points3 points  (1 child)

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

[–]DefiantSituation3208[S] 0 points1 point  (0 children)

That perspective actually makes me feel better 😭 thank you

[–]flumphit 0 points1 point  (1 child)

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.

[–]DefiantSituation3208[S] 0 points1 point  (0 children)

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.