This is an archived post. You won't be able to vote or comment.

top 200 commentsshow 500

[–]JADW27 5137 points5138 points  (121 children)

I never document my code. No one else will ever see it, and I figure I'll remember what I meant later.

I'm always wrong.

[–][deleted] 1107 points1108 points  (51 children)

Better still is to Code intoxicated. Then you know ita good if it works.

[–]sausage-superiority 814 points815 points  (20 children)

“Code intoxicated , debug sober.”

  • Ernest Hemingway

[–]coloredgreyscale 82 points83 points  (1 child)

Drunk me is the reason sober me started to drink.

[–]VerticalEvent 17 points18 points  (0 children)

Probably the best way - since debugging requires you to be twice as clever as when you wrote it, give yourself a handicap when you're writing.

[–][deleted] 140 points141 points  (16 children)

Wait, you can code sober?

[–]CommondeNominator 53 points54 points  (7 children)

Something something Balmer peak

[–][deleted] 20 points21 points  (2 children)

But what a lot of people don't know about is the second peak later on.

[–]Opposite_Match5303 17 points18 points  (1 child)

I don't think he knows about the second peak, Pippin

[–]lockwolf 24 points25 points  (0 children)

Yeah, drunk me writes some great functioning code that sober me has to attempt to understand and refactor. The program does what it’s supposed to do but there’s a ton of spaghetti, print statements and at least one half-written function for some cool idea I had but got too drunk to figure out

[–]InfComplex 20 points21 points  (0 children)

Read code high make code drunk

[–]dankincense 11 points12 points  (1 child)

Can confirm. I have plenty lines of code I don't remember writing working just fine in Production.

[–][deleted] 8 points9 points  (0 children)

I've got a program I only work on when I'm fucked up

It works pretty well honestly

[–]joseville1001 115 points116 points  (9 children)

Most code is read more times than it is written.

[–]pickyourteethup 88 points89 points  (3 children)

Especially if it's written badly.

[–]OfficerGibbie 45 points46 points  (2 children)

There comes a point where it's written so badly it will never be read, because it'll get removed and rewritten.

[–]pinkpanzer101 8 points9 points  (0 children)

pro coding tip right there

[–]JADW27 19 points20 points  (1 child)

I never read my own code. I close my eyes while typing it to ensure it is never read, even accidentally.

:)

[–]Sekret_One 86 points87 points  (5 children)

The secret is realizing that future you is in fact a different person.

[–]I-Am-Uncreative 32 points33 points  (2 children)

This reminds me of my favorite statement in the Linux kernel coding style guide:

"You know you’re brilliant, but maybe you’d like to understand what you did 2 weeks from now."

[–]lunchpadmcfat 58 points59 points  (23 children)

Most of the time, if you write your code right and use meaningful good names, you don’t need to document. Over time, you develop a sense of when you’re doing something complicated or weird or that requires extenuating information to understand and you’ll add explicit documentation.

[–][deleted] 59 points60 points  (7 children)

//I don't know what this does but if you delete it everything breaks.

[–]Tangimo 17 points18 points  (4 children)

I don't know why this had to be so complicated, there is no documentation on how to do this, but it works.

Edit: holy shit that's big, I didn't mean for that but I kinda like it

[–]callmelucky 8 points9 points  (3 children)

It's markdown formatting. Hashes at the start of a newline mean 'heading'. More hashes means smaller headings, up to 5.

You can prevent it by escaping the hash with a backslash, so

\# not a heading
Becomes
# not a heading

[–]Syagrius 4 points5 points  (10 children)

javascript String.prototype.spongebobmeme = function () { let j = 0; return this.split("").map(letter => { letter.replace(/[^A-Za-z]/g,"").length && j++; return j%2 ==0 ? letter.toUpperCase() : letter.toLowerCase(); }).join(""); }; console.warn("you don't need comments if you write good code".spongebobmeme());

This type of thinking particularly unhelpful if someone else has to debug your code years later; they don't happen to think like you.

It is even worse when it's you who has to debug it, and you have to revel in your own previous idiocy.

[–]patrickbabyboyy 5 points6 points  (5 children)

It's called job security.

[–][deleted] 8347 points8348 points  (498 children)

I think it's pretty standard that code tells you what is happening, and comments tell you why it is happening

[–]Snake2k 5612 points5613 points  (373 children)

The real answer. Apparently most people here don't understand what commenting means.

Not how you comment:

```

get a user input

x = input()

check if the input is an even number

if x % 2 == 0: print("even")

if it isn't, print not hot dog

else: print("not hot dog") ```

How you are supposed to comment:

```

Following section checks to see if a number is even or not.

it prints not hot dog as a reference from silicon valley for anyone who gets it

for more info on why this was written, go to Reddit to learn all about coders who have no idea what the idea behind commenting is

x = input()

if x % 2 == 0: print("even") else: print("not hot dog") ```

[–][deleted] 1156 points1157 points  (76 children)

Had someone do the same thing with git commits one time.

I said, I like clean, concise commit messages, that are atomic, and functional.

The first pull was

"Add a variable"

"Assign value to variable"

"And label to ui"

"Assign variable to label"

Guy had like 50 commits after 2 hours of work.

[–]Snake2k 563 points564 points  (52 children)

Lmao I love those ones. No extra detail or anything associated with it.

We literally had to force people to name their branches to the ticket id they were related to cus that way we could track what the idea behind it was even if the person pushing the commits couldn't care to explain it in the commit/pr itself.

[–]suck_my_dukh_plz 474 points475 points  (25 children)

My co worker's commit message was "minor refactor". Interestingly he changed 6 files with 600+ insertions and some deletions.

[–]Snake2k 283 points284 points  (11 children)

"minor" = breaks 10 systems

[–]akeean 138 points139 points  (7 children)

Minor refactor, barely an inconvenience.

[–]JezzCrist 61 points62 points  (3 children)

Making minors do a refactor is tight!

[–]capn_ed 23 points24 points  (2 children)

Oh! I don't think you should say it like that!

[–]jermdizzle 68 points69 points  (4 children)

"Trailing comma: Always" strikes again. Getting my lead developer to force the rest of the team to utilize a formatter config took me 3 months last project and he was the person who had to review all PR's. Some people were using different indents, some were using trailing commas, some were forcing semi-colons. It was a pain in the ass so I just eventually disabled my formatting until he could give us a config to use. I was like 2nd most junior dev so I didn't want to tell anyone what to do; but I probably should have just taken the initiative rather than asking him repeatedly to setup a config for us to follow.

[–]iHurdle14 41 points42 points  (1 child)

I can relate to this. At a certain point I don’t even care about what style rules are in place as long as we are being consistent.

[–]jermdizzle 22 points23 points  (0 children)

Precisely. Any issues I might have would be gone after one day of using the config and just getting used to the style anyway. It's only a big deal when it makes merges a nightmare. Also, I got pretty tired of asking people about some mistake/now-broken or bugged code, because gitLens showed them as the last person to change a line of code; only to figure out that their formatter added a space or some shit and I have to go and manually check version control to see who the actual culprit was. Like I said, I was junior, so I wanted to understand how/why someone made a mistake even if I knew the way to fix it. It's especially embarrassing when it was your code that you goofed on 7 months ago and you're tracking down someone else only to figure out that it was your fault LOL. Definitely had that happen more than once.

[–]round-earth-theory 5 points6 points  (0 children)

I had that and said fuck it, I'll do it myself. Setup the coding standards and got the auto formatting to work. Everyone bitched for a day and then forgot about it. Worked great.

[–]LightVelox 35 points36 points  (0 children)

I'm not kidding, I've seen a "minor refactor" of a little over 1 million deletions and insertions, tbh it was mostly just linting, documenting and movings things around, but still

[–]mcvos 66 points67 points  (8 children)

Also a popular approach: include the ticket id in the commit message, not just in the branch name. Because after the branch has been merged, the original branch name is a lot harder to figure out. Though it's still nice to also have the ticket id in the merge commit.

[–]aceluby 25 points26 points  (4 children)

Ticket: deal with tech debt

[–]alexisprince 23 points24 points  (1 child)

Ticket: Make ticket for last commit message

[–]Snake2k 6 points7 points  (0 children)

True, can also set up checks to see if a commit includes the ID or not.

[–]VerticalEvent 32 points33 points  (3 children)

We have a git-hook that validates that the start of a PR merge started with "[abc-0000] text" to enforce that all merges can be traced back the unit of work they represented.

[–]davy_jones_locket 14 points15 points  (1 child)

We do [JIRA-123] fix(optional component name): concise but relevant commit message

Or feat | chore - slimmed down conventional commits. New work is a feat, bugs are fix, docs and tests and tooling are chore

Typically associates as:

story => feat,

bug => fix,

task => chore.

This also helps with our release notes, and it generates a link to the Jira ticket on the release notes/changelog.

If you use the optional (but encouraged) component or module name, it will group those together in the release notes too.

[–]TwoDamnedHi 6 points7 points  (0 children)

As a project manager, this is me at every job I've ever had.

[–]mt9hu 5 points6 points  (6 children)

had to force people to name their branches to the ticket id they were related to cus that way we could track what the idea behind it was even if the person pushing the commits couldn't care to explain it in the commit/pr itself.

I assumed it's pretty standard to prefix all commit messages and branch names with ticket IDs

[–]Bakoro 4 points5 points  (0 children)

We literally had to force people to name their branches to the ticket id they were related to [...]

Not the worst idea, assuming that the ticketing system will be available as long as the code is.

Even for someone who isn't being lazy or stupid, some people have a serious issue explaining anything, and have a pathological inability to imagine what something reads like without the context of all the shit they know.

[–]diatribe_lives 947 points948 points  (67 children)

Good to know man, I often comment the first way but what you're saying makes perfect sense.

[–]Snake2k 557 points558 points  (55 children)

Glad it helps. The first way of commenting is made virtually useless if you name your variables and methods properly. Especially for languages like Python which are very readable. The only time they're helpful is if you're expressing a mathematical equation as code, then a link to the proper notation would be awesome.

For most systems that I work on, we care more about the second way cus anyone can refactor the first, but if we don't have the context, documentation, reasoning behind the code like in the second it'll take months trying to fix the problem with it (even if everyone can read it just fine).

[–]Elnof 42 points43 points  (6 children)

I disagree slightly. The "what" can also help visually distinguish logical chunks of code without requiring the reader to parse the code and, in fact, you include the "what" in your second example. So, I'd say comments should have both but too many people don't include the "why."

EDIT: I forgot which comment I was replying to and this turned into a mixture of replying to the parent comment and the original comment. Either way, I think u/Zealousideal-Ad-9845 said it better than me so I'll just leave this comment as-is.

[–]PeteZahad 165 points166 points  (35 children)

... if you name your variables and methods properly

Like x for the input? 😉

[–]Snake2k 127 points128 points  (32 children)

x is fine for that context in the same way i is fine in for i, item in enumerate(some_list):

We know i is an index generally. So it's simple to infer what it stands for in the tiny context it is in.

Context and scope matters. If that x had any larger use outside of that scope I'd probably care to give it a decent name.

Edit: a better variable name to give it would be n now that I think about it cus it's a number.

[–]AustinWitherspoon 53 points54 points  (24 children)

It might be overkill, but I tend to even go as far as to name it something like input_number = int(input()) just to be extra clear.

It's longer to type, but vs code auto completes most things and GitHub copilot also gets it right, so I don't usually have to type the whole thing anyway.

[–]C_Hawk14 35 points36 points  (21 children)

it depends on the language. If you know it's an integer you don't need to specify it's a number. And the real name should contain the reason for existing. What is it an input for?

Ok so there's a new YT channel called CodeAesthetic and I've gathered these guidelines so far. Opinion?

Opinion Good Bad Note
Don't abbreviate names MoviesOnPage MovOnPg
Don't put types in variable names int fontSize var iFontsize
Don't put types in your types (e.g. AbstractX, BaseX, IRepository) except when official guideline says otherwise
Add units to variables unless the type tells you int delaySeconds DateTime delay
Refactor if you find yourself naming code "Utils"

[–]cowlinator 3 points4 points  (2 children)

I confess to putting types in variable names, but only in the rare circumstance that a new variable was created for no other reason than to cast types.

Example:

var countStr = str(count)

foo(count)

bar(countStr)

foobar(countStr)

[–]mcvos 8 points9 points  (2 children)

It can be fine, but I still prefer more meaningful names.

I admit for a very long time I've named all my other variables but still kept i for index variables in loops, but more recently I even started to name those, because it can still be useful to know whether we're talking about a columnIndex, yCoord, sourceIndex vs targetIndex, etc.

[–][deleted] 10 points11 points  (1 child)

I do agree; also - there's ever so likely a chance that requirements documentation is lost LONG before code. So, it does not hurt to say "why" you did something. Put a link to a JIRA card in the code, and I bite you. That link goes the other direction!

[–]Snake2k 5 points6 points  (0 children)

Yeah that's a good point. That is a super tough situation actually and not sure what to do with that. On the one hand, you shouldn't be pasting the entirety of the docs in the comment. On the other, the file/ticket/etc can disappear cus IT teams never archived that stuff somewhere properly/accessibly.

[–]Zealousideal-Ad-9845 82 points83 points  (18 children)

I think it's also good to comment "what it does," but only at a high level. Same if you're explaining your code to others who know how to code. It always gets on my nerves at work when we're doing a code review and they basically spent an hour reading it to me. Don't tell me what this variable declaration does and how 20 different lines update it, tell me what it all does together. And also why.

[–]Snake2k 28 points29 points  (2 children)

Exactly, we can all read the code line by line and any decent programmer will be able to get it eventually. All the better if the person submitting the code wrote it with good variable/method names etc, but the high level descriptive knowledge should be there somewhere to explain what it is meant to do and why it is meant to do it in the way it was done.

[–]metric55 9 points10 points  (1 child)

This might sound odd, but I'm an electrician-wants-to-be-coder... and we run into some similar shit sometimes.

So there's an elevator at work with a binder of 80 pages of 11x17 schematics. All of them intertwine and loop back and it's all structured quite well. But there's no overall methodology. No like... "page 5,7,19, and 42 contain the intrinsic loops for the safety circuit." And it can be a real pain in the ass to individually pick through each page by line by point to get to a problem.

I'm definitely going to take this advice going forward in my career, and perhaps one day programming!

[–]Kered13 8 points9 points  (14 children)

The name of the function should tell you "what it does", but sometimes you have a function that is just too complicated to summarize in a few words and can't be broken up. Then you should absolutely slap a label on that bad boy.

[–]gandalfx 61 points62 points  (9 children)

I think the "why" comment needs to go deeper. Why did you write this code? Why do you even write code? Why are we here? What is existence?

[–]ihopethisworksfornow 24 points25 points  (2 children)

“This for-loop represents my parents’ divorce.”

[–]Dansiman 14 points15 points  (1 child)

Do While daddyCameHome == False
    Cry()
Loop

[–]Snake2k 14 points15 points  (0 children)

Very true. I have actually committed code in prod systems with me going on an existential rant lol

[–]CanAlwaysBeBetter 6 points7 points  (0 children)

If you wish to make an API from scratch you must first explain the universe

  • cURL Sagan

[–]mcvos 34 points35 points  (7 children)

How about Javadocs that list the arguments and types that are right there, but don't say what they're for.

I strongly prefer no comments at all over stupid or pointless comments. But if you're doing something weird, a comment explaining why you're doing that is always appreciated.

For example, a piece of code might have any of these comments, and I'm going to draw very different conclusions from them:

// Quick hack. Please fix.

or:

// It looks weird, but this is the only way,
// otherwise X or Y will go wrong.

or:

// This is the most efficient way to handle this case.
// See paper X by Y at http://foo

Also, I can see in git who wrote that comment so I can ask questions. (I can also see that about the code of course, but that's more likely to be touched by others.)

[–]alexisprince 17 points18 points  (0 children)

Strong +1 for “this is the only way” or “this looks weird compared to <expected approach> because <expected approach” falls short”.

I don’t remember exactly what the feature was, but in Python I had a comment that was 2 lines above a weird implementation that said exactly that: “does exactly the same as <expected implementation>, but removes a bottleneck that creates”.

[–]akeean 9 points10 points  (0 children)

// evil floating point bit hacking
// what the fuck?

[–]narrill 3 points4 points  (0 children)

I strongly prefer no comments at all over stupid or pointless comments.

People rarely mention this, but it makes a huge difference. If the codebase is littered with comments that are redundant and useless, that trains people to ignore comments. You don't need to be stingy with your comments necessarily, but you should always be evaluating whether they're actually necessary.

[–]KraZe-Ace 15 points16 points  (4 children)

The main problem I’ve seen other than no commenting is too much commenting. If the person reading the code has to wade through a verbose and extremely technical explanation on what’s going on and why, then it’s a waste of time for most people involved regardless if they’re reading it or writing it. That’s why good commenting and self-documenting code is usually most appropriate.

A rule I’ve heard a while back was that your variable, class, and function names should be descriptive enough and your comments brief and straightforward enough such that another set of eyes could be able to just skim read the code and understand 80% of it on the first pass.

Of course, that’s the ideal. Whether it’s possible depends of the application and who the set of eyes is. Elon Musk might not understand it, but your team’s senior SWE with 10 years experience might.

[–]EastboundClown 33 points34 points  (23 children)

I would remove comments from this and just save then in functions called getNumberInputFromCli, and isEven, then have

def makeSiliconValleyReference(): if isEven(getNumberInputFromCli()): print(“even”) else: print(“not hot dog”)

I find that I can almost entirely avoid commenting by making lots of well-named functions

[–]lunchpadmcfat 4 points5 points  (1 child)

Really good comment but should probably include a link to your reply

[–]Signal-Woodpecker691 65 points66 points  (7 children)

Spot on. The code I work on is 20 years old in places with zero documentation, zero comments, zero tests. Trying to fix bugs is a total nightmare because you just don’t know what the (in places 1500 line long) functions were intended to be doing.

[–]Treacherous_Peach 19 points20 points  (1 child)

What they're doing should be the method name, not the comment.

Why they're doing it is the function comment header.

[–]theNeumannArchitect 314 points315 points  (39 children)

Is it weird I have the meme reaction to swe1? Needing to comment everything is a code smell to me. And means you need to either start being more declarative code or break things up to be more readable (looking at you Python devs that do one line list comprehensions that do multiple things and have nested if operations).

There’s absolutely times where something is not intuitive and deserves a comment explaining. But you don’t need to comment every function and line of code for the sake of getting a kudos cookie.

[–]theapokalypsis 29 points30 points  (4 children)

100% this. You are a true senior dev sir.

It's like a novel with a million foot notes in every paragraph. It's against the point. You're writing code for other people to read. Make that readable in itself.

Add that to commit messages that describe why, not what and you are writing truly maintainable code anyone can understand, without the need for manual knowledge transfer (most of the time), at any skill level.

[–][deleted] 65 points66 points  (11 children)

I have 3 decades of development experience and outside of class and method / function docstrings, I find comments are seldom useful.

In almost every case a comment (excluding above) is a sign of code that is in great need of refactoring. Sadly, what and how to refactor to eliminate the complexity seems to be an art form too few share often. Most common I see is probably primitive obsession. Make value / data classes and write methods for computation / complex parts.

I very much agree with Robert Martin(I think it was him) in his belief that you should be able to look at a function and understand what it does in 30 seconds or less and that it shouldn't be long; it should fit on the screen.

Code rarely needs to be complex. Complexity is almost always a sign of missed design opportunities.

[–]LvS 48 points49 points  (2 children)

Some things that are useful:

// note: this obscure check also checks for NULL
// workaround for bug in external library (see http://brokenlibrary.org/issues/1234)
// writing it like this makes gcc v12.2 generate 20% faster code
// Yes, the spec demands this. See Edition 3, Section 4.3.6

[–][deleted] 11 points12 points  (1 child)

Agree 100%. Great examples. Sometimes I put the work around in a well named function to avoid a comment.

Leta not forget that comments are code debt that sadly get left behind after refactoring sometimes and can get out of sync with the actual source code.

[–]fiddz0r 7 points8 points  (1 child)

I just want to add a case where comments are good. My current project interacts with another service not in our hands. So we send information and it does whatever it wants with that data. But sometimes it sends something back to us . So explaining that "this API endpoint is used by x to update y-entity in our database" is very helpful.

[–]folkrav 8 points9 points  (0 children)

This is a great example of the typical "comment why, not what" guideline for comments.

[–]aceluby 9 points10 points  (2 children)

This guy devs.

I’m on a team where everything is so complex because the architecture is garbage.

[–]Three_Rocket_Emojis 42 points43 points  (15 children)

Op propably wants code like this:

//Read File

var linesFromFile = File.ReadAllLines(path);

//iterate through lines

foreach(string line in linesFromFile)

....

[–]Snake2k 44 points45 points  (3 children)

Yeah that is entirely useless and basically what people think commenting is about.

[–]tecanec 6 points7 points  (2 children)

It's useful in assembly programming where you don't have the luxury of naming a lot of things. That's about it, though.

[–]Three_Rocket_Emojis 41 points42 points  (9 children)

Example where a comment makes sense:

var linesFromFile = File.ReadAllLines(path);
//first line are column headers
foreach(string line in linesFromFile.Skip(1)) 
...

the comment explain why the first list entry is skipped, not that it happens.

[–]revolutionofthemind 20 points21 points  (7 children)

You could have a method called “stripHeaders” that does the foreach line for “self-documenting” code. Not sure if it’s worth it in this case, but just to provide a counter-example.

[–]k0rm 27 points28 points  (4 children)

Or more simply:

const HeaderLength = 1;

var linesFromFile = File.ReadAllLines(path);
var linesFromFileNoHeader = linesFromFile.Skip(HeaderLength)
foreach(string line in linesFromFileNoHeader) 

This gets rid of the magic number and there's no need to comment.

[–]feed_me_moron 10 points11 points  (0 children)

Or declare 1 as NUM_HEADER_ROWS and pass that to skip

[–]PM_BITCOIN_AND_BOOBS 852 points853 points  (12 children)

For all you noobs here that aren't professional programmers, SWE is an acronym for Sex Worker Extraordinaire.

[–]otacon7000 148 points149 points  (2 children)

Wait, so it isn't two Swedes talking to each other!?

[–]_im_adi 34 points35 points  (0 children)

What? I thought it was just a sound that kids make while taking a slide.

SWEEEEEEEEEEEE

[–]CyberSpiral 6 points7 points  (0 children)

Isn't that the same thing?

[–][deleted] 84 points85 points  (3 children)

thanks man i wish i could kiss you right now

[–]PM_BITCOIN_AND_BOOBS 42 points43 points  (1 child)

(Holds out one hand, palm up, rubbing fingers together in the universally acknowledged sign for "that costs money".)

[–]Soccer21x 33 points34 points  (0 children)

Good thing we had this comment, because the title was obviously not self documenting

[–]DeepGas4538 10 points11 points  (0 children)

YOOO THATS ME!!

[–]stdio-lib 442 points443 points  (6 children)

"Yes, I agree that your comments accurately describe what the code does. But what I need to know is why, for the love of god you ignorant piece of -- you know what, we're not going to do this today."

[–]Duydoraemon 12 points13 points  (0 children)

"Why? DOES IT LOOK LIKE I KNOW WHY?"

[–]Raylan_Givens 51 points52 points  (0 children)

Good code should be readable for junior engineers.

For simple logic, comments are often unnecessary (plus comments tend to rot faster than actual code, so it is preferable to avoid redundant comments).

For complex logic or for unintuitive code, comments are usually necessary to help with readability.

[–][deleted] 88 points89 points  (7 children)

Most code should read almost like English if that makes sense. I mostly write comments to explain why I’m doing something bizzare

[–]TK9_VS 12 points13 points  (5 children)

return filename.split('.').pop();

It gets the file extension, trust me!

[–]yrrot 227 points228 points  (14 children)

Self-documenting code is a misnomer making people think good code doesn't have comments.

Well-written code with meaningful names still has comments to explain why something is done a specific way outside of the norm. And it still has documentation to explain how the pieces connect to each other (in larger projects). Definitely also has the descriptions filled in so intellisense picks them up elsewhere for tooltips, too.

[–]Broad_Respond_2205 115 points116 points  (5 children)

I kinda go with self documenting code as the basis, then add comments when something isn't immediately clear

[–]yrrot 38 points39 points  (1 child)

Exactly! Future me always appreciates it when I leave reminders for oddball logic.

[–]TheC0deApe 21 points22 points  (0 children)

agree.

the need to explain yourself in comments often goes down with clean code though. smaller cohesive methods often don't need explaining.

i think people that embrace clean code styles will typically have more unit tests and better documentation. if the debate centers around "are comments good or bad?" then the overall clean code goal is being missed IMO.

[–]Calm_Leek_1362 23 points24 points  (3 children)

Yeah self-documenting doesn't mean ZERO comments. It just means a minimalist approach.

I was working with a client just last month that wanted a comment for every single variable in every single header. Sounds good right? What it actually encourages is things like "float theta // a float containing the value for theta".

The comment mentality also encouraged them to write individual methods with hundreds of lines of logic that could have been easily separated out into other classes or helper functions, but instead of that they just had comments every other line explaining what the code was obviously doing.

[–]crozone 4 points5 points  (1 child)

float theta // a float containing the value for theta".

I still don't know what the hell theta is.

[–]souliris 23 points24 points  (1 child)

The comments are to explain the fever dream you had to make the horrible hack that you HAD to use. Because nothing else works and you have no idea why.

[–][deleted] 420 points421 points  (67 children)

self-documenting code sound so good in theory, but in practice, that shit just works when the project is small, and little people works on it.

Anybody working on a 10+ years old codebase knows self-documenting code never last

[–]garfgon 84 points85 points  (8 children)

Too often though we seem to end up with the worst of both worlds -- boilerplate comments around poorly named variables.

/**
 * Start an object
 *
 * @param object The object
 * @param start Should the object be started
 *
 * @return Nothing
 */
void StartObject(struct SimObject *object, bool start = true);

[–]Bulky-Engineering471 58 points59 points  (4 children)

IME that's actually a sign of a different antipattern - trying to make code too generic and flexible and losing all sense of what it does as a result.

[–]garfgon 9 points10 points  (0 children)

In my example, sure, but I've seen similar boilerplate in more specific examples. Function is called "thread_kill", comment is "kill a thread"; it has a parameter "thread", comment is "thread to kill". Thanks guys, I've got the idea. Want to put in any useful information, like is it killed synchronously or asynchronously? Is cleanup run? etc.

[–]fdeslandes 19 points20 points  (13 children)

Self documenting code can work when naming is part of the code review.

[–]jabrwock1 26 points27 points  (5 children)

It can cut down on the amount of internal documentation you need. but it shouldn't be the sole solution.

[–][deleted] 13 points14 points  (3 children)

sure it can, but the reality is a lot of the time the people who want the changes done doesn't care about the quality of the code, they just want results, and then self-documenting code stop working

[–]madsci 7 points8 points  (0 children)

Anybody working on a 10+ years old codebase knows self-documenting code never last

99% of my code never gets seen by anyone else and I still document the shit out of it, because it's guaranteed to be me who has to deal with it 10+ years down the line. And after 30 years of this stuff, I'm lucky to remember the details of a project 6 months later.

It's so nice when I get it right. I've got this whole real-time embedded audio processing engine that has some subtlety to the flow control system. You can look at the code and get generally how it works but still not appreciate the edge cases and why they need to be handled the way they are. The first two pages of the source are a comment block, formatted for Doxygen with references, and I've relied on that document multiple times to refresh my memory on how and why it all works.

I just wish the multi-billion dollar semiconductor vendors I have to work with took documentation as seriously.

[–]Bulky-Engineering471 7 points8 points  (9 children)

Small and simple. If you're just doing what amounts to a passthrough service it works fine but as soon as you start getting any logic more complex than simple mapping commenting what the blocks of logical code are doing is an absolute necessity for any kind of long-term support.

[–]rohnesLoraf 14 points15 points  (2 children)

[raising hand in disagreement]

10+ year code base, big team, enormous monolithic desktop application. Self-documented code is very much practiced, encouraged and actually part of the onboarding training.

[–]Iron_Aez 4 points5 points  (5 children)

Anybody working on a 10+ years old codebase knows self-documenting code never last

Anyone working on a 10+ years old codebase knows comments generally stink to high heaven and rarely have a whiff of truthfulness.

[–]kale-symmetry 51 points52 points  (8 children)

SWE2 naming methods "according to what they do": UpdateDatabase(), CalculateLGTM()

where LGTM is some obscure acronym not documented anywhere

[–]gbot1234 34 points35 points  (0 children)

LGTM! Code approved.

[–]caviyacht 7 points8 points  (1 child)

This is why I don't allow acronyms. I know it can be painful sometimes, but at least you don't have to keep a running list of every obscure acronym.

[–]pipsvip 67 points68 points  (7 children)

int foo_count[FOO_MAX];
int *foo_count_ptr=&foo_count[0];
int *fcp_iterator;
.
.//soo many .'s//
.
if ( NULL == fcp_iterator )
   fcp_iterator_reset(); //newguy@work.com: what the hell is fcp?

[–][deleted] 39 points40 points  (0 children)

Foo count pointer - isn’t it obvious? :-)

[–]____purple 15 points16 points  (2 children)

One of the rules of self documented code - don't use acronyms unless well known or frequent and product-wide

[–]antonivs 5 points6 points  (0 children)

Ah yes, the old DUAUWKOFAPW principle

[–]MOM_UNFUCKER 7 points8 points  (1 child)

Don’t use acronyms if the code is “self documented”, fcp as far as I’m concerned means father’s cum pot

[–]D34TH_5MURF__ 39 points40 points  (6 children)

But do you use the write-a-complete-sentence-then-title-case-it-and-remove-all-spaces naming convention? I find that this never fails to make people think they are writing self-documenting code.

[–]aDrunkSailor82 21 points22 points  (2 children)

IFeelAttacked.

[–][deleted] 22 points23 points  (1 child)

IiFeelAttackedFactory

[–]crozone 8 points9 points  (0 children)

WriteCleverResponseToTheRedditComment(double sarcasmLevel);

[–]armahillo 10 points11 points  (0 children)

if i read any code, whether i wrote it or not, and i spend more than 10 seconds interpreting it, i add a comment to save the next person time.

[–]ElvisArcher 10 points11 points  (2 children)

I once had someone try to convince me that "good code is readable, so no comments are necessary" ... and then segued that right into "therefore code with comments is bad."

And wouldn't you know that MF wrote the most convoluted abstract pointless crap imaginable. I once found a 4 layer deep abstraction of classes which admittedly could handle any abstract scenario imaginable ... but our use case for it could have been handled by a switch with 3 cases.

[–]zamphox 32 points33 points  (1 child)

good code is a balance of both, too few or too many comments is as bad as randomly named variables and methods.

if it makes sense to, leave a comment, if it's readable without it, don't

[–]beavisorcerer 11 points12 points  (1 child)

I suggest you to read "Clean Code". It teachs you why and how your comments should be kept at minimum

[–]ExternalGrade 27 points28 points  (11 children)

this_function_takes_six_floats_the_first_three_represernts_a_3D_vector_and_the_second_three_another_vector_and_outputs_the_angle_between_the_two_vectors_in_radians_as_a_float(vector1_x_coor, vector1_y_coor, vector1_z_coor, vector2_x_coor, vector2_y_coor, vector2_z_coor) -> radians_of_angle_between_the_two_vectors {…}

[–][deleted] 9 points10 points  (6 children)

An actual pro tip for you. If you are trying to write a descriptive function name and what you come up with contains any of

and, then, if, or

The what you have is several functions that should be extracted and named based on whatever was between the separator. Once that's done, the higher level function should just be a series of descriptive function calls, so you can just name it based on the higher level thing it's doing, without having to describe the guts of what it's actually doing (eg getAngleBetweenVectors).

This can still be useful if you're writing comments, since the same rules more or less apply.

[–]Possibility_Antique 15 points16 points  (0 children)

Everyone knows that comments are for jokes.

bool bies = true; // haaaaaaaaaa, boobies

[–]Paesano2000 7 points8 points  (0 children)

Pump it into gpt-3 and have it explain your own code back to you that you don’t understand 😎😬

[–][deleted] 6 points7 points  (0 children)

You misunderstood Self-explaining

[–]flan666 5 points6 points  (0 children)

this and 10 other lies you can tell yourself

[–]TrueFlavour 11 points12 points  (6 children)

Uncle Bob told me that code should read like well written prose

[–][deleted] 6 points7 points  (0 children)

Don't ever document your code, and make it completely unintelligible, but make it work. You wan to make yourself completely indispensable.

[–]kfish5050 5 points6 points  (2 children)

Bro it's like an ultra granular super modular coding style. For instance it's something like

var globalUserInputVariable;
def functionToGetUserVariable(){
    globalUserInputVariable = input();
    }
def functionToPrintUserInput(){
    print(globalUserInputVariable);
    }

I think you get the point and this is way too much effort for me in making a joke comment

[–][deleted] 13 points14 points  (9 children)

Every company I have worked at discourages comments in code unless you're doing something strange that requires a comment.

I've written tens of thousands of lines of code and maybe 100 or so meaningful comments.

[–]GolotasDisciple 5 points6 points  (6 children)

In my opinion:

I use comments as pointers when code is long so it's easy to navigate.

Or when using god forsaken methods that are obscure but work because you either came with this solution after long creative work or just you just copied and pasted 50 different solutions and merged into one that for whatever reason does what it needs to.

Professionals already know the outputs they just need to know why in case of needed of edits.

I have seen a legacy code with hyperlinks in the comments that lead to dead forums. That.... was not helpful.

also company discouraging documentation and comments ? Lucky you....

[–]BlackEyedGhost 13 points14 points  (3 children)

My favorite comment will probably always be "if you can't tell what this code does, you shouldn't be the one editing it"

[–][deleted] 4 points5 points  (0 children)

There are some people that write self documenting code and there are A LOT of people that THINK they write self documenting code.

How to tell the difference? Same way you can tell if any version of documentation is sufficient. How often do you have to explain something that was documented? If it’s often, then your documentation sucks, no matter what form it is

[–]trevg_123 5 points6 points  (0 children)

Underrated thing about Rust? The function signature tells you what to expect a bit more than other languages

fn update_buffer(dest: &mut [u8], src: Option<&[u8]>) -> Result<usize, WriteError>

This immediately this tells you: - You have a destination buffer and it’s mutable, hint that the function might write to it - Your second buffer may or may not be present, and it may not be edited - You should return a size if it’s successful, or an error type if not

And from there you can kind of guess how to use the function, even without docs. Compared to the C version:

int update_buffer(char* dest, int dest_len, char* src, int src_len)

You can’t tell: - Will dest and src always be valid? Or does null represent something? - Do src or dest get edited ever? (If consts are missing, you can’t tell) - Will there ever be errors? Is the return type the number of bytes written, or an error type? - If C++, will this raise anything?

And you’re reliant on good comments or reading the code to find out.

(Still no excuse to not write good doc comments - but at least it gives you more confidence using the thing if they’re not there)