1178
Comenting code (lemmy.ml)
top 50 comments
sorted by: hot top controversial new old
[-] russ@cupoftea.social 1 points 12 hours ago

@Vordimous @linuxgal when I see this sort of thing when reviewing PRs, I write words to the effect of "tell me WHY it's doing that, not WHAT it's doing". The "what" is usually obvious from the code and thus not worthy of comment. The "why" will enlighten your colleagues (and future you).

[-] piko@chaos.social 2 points 5 days ago

@Vordimous Wait for daylight saving time...

[-] Vordimous@lemmy.ml 1 points 4 days ago

Is that when all of the devs write the comments on the line after the code?

[-] chautalees@lemmy.world 2 points 6 days ago

When you ask a Dev to test their own code

[-] x00za@lemmy.dbzer0.com 2 points 6 days ago
// Open file
fopen();
[-] sjh@sh.itjust.works 1 points 6 days ago

Commenting code is a super important habit to get into—it not only helps others understand your thought process but also makes it easier for you to pick up where you left off if you revisit the code later. Plus, well-commented code can significantly reduce the onboarding time for new developers on a project. Remember, comments should explain the "why" behind the code, not just the "what." For instance, stating why you chose a particular algorithm or data structure can be far more helpful than just labeling it. According to a study by SmartBear, 44% of developers regard poorly documented code as a top cause of project delays, so it’s definitely worth the extra effort!

[-] doktormerlin@feddit.org 1 points 6 days ago

But it's also important to learn that comments should be brief and concise. We have one file from an ex-dev in which there are 750 lines of code and 2000 lines of comment, when someone wants to maintain this code they always have a hard time because this many comments are taking up so much screen real estate that you can't find the code that actually does stuff

[-] shasta@lemm.ee 2 points 6 days ago
[-] ZILtoid1991@lemmy.world 1 points 6 days ago

I only have a 3k monitor, and I can manage it. Sometimes I comment line-by-line even.

[-] essteeyou@lemmy.world 122 points 1 week ago* (last edited 1 week ago)
/**
 * Gets the user
 **/
fun getUser() {
    return this.user;
}
[-] some_guy@lemmy.sdf.org 33 points 1 week ago

I'm sorry, I don't think I understand what's happening here…

[-] essteeyou@lemmy.world 29 points 1 week ago

Let me find the sequence diagram...

[-] jaybone@lemmy.world 12 points 1 week ago

You need the requirements doc from marketing. Then it will all totally make sense for sure. No cap.

load more comments (1 replies)
[-] lord_ryvan@ttrpg.network 8 points 1 week ago* (last edited 1 week ago)

Okay now I get the joke.
I hate these kind of people.

By the way, your ``` both need to be on their own, separate line

load more comments (5 replies)
[-] JasonDJ@lemmy.zip 84 points 1 week ago

My comments are just the code that didn't work but I don't want to delete yet because I might make it work except I never will be cause I already rewrote it so it does.

[-] Sparky@lemmy.blahaj.zone 50 points 1 week ago* (last edited 1 week ago)

Hey thanks for reminding me I made a clock squared in blender about 2 years ago

yes there is an error in the image, and no I'm not telling you where it is

[-] oo1@lemmings.world 45 points 1 week ago

at 6 it says 12:30

[-] xmunk@sh.itjust.works 12 points 1 week ago

1 o'clock and 10 o'clock are the the wrong angles.

load more comments (2 replies)
load more comments (7 replies)
[-] goatmeal@midwest.social 33 points 1 week ago

I know I’m probably doing it wrong but this is how I feel whenever I write unit tests

[-] jonathanvmv8f@lemm.ee 24 points 1 week ago* (last edited 1 week ago)

Asking as a newbie programmer: how do you suggest we write comments that explain the 'why' part of the code? I understand writing comments explaining the 'what' part makes them redundant, but I feel like writing it the former way isn't adding much help either. I mean, if I created code for a clock, is writing "It helps tell what time it is" better than writing "It is a clock" ?

It would really help if someone could give a code snippet that clearly demonstrates how commenting the 'correct' way is clearly better than the way we are used to.

[-] pixelscript@lemm.ee 21 points 1 week ago* (last edited 1 week ago)

I recognize three kinds of comments that have different purposes.

The first kind are doc block comments. These are the ones that appear above functions, classes, class properties, methods. They usually have a distinct syntax with tags, like:

/*
 * A one-line description of this function's job.
 *
 * Extra details that get more specific about how to use this function correctly, if needed.
 *
 * @param {Type} param1
 * @param {Type} param2
 * returns {Type}
 */
function aFunctionThatDoesAThing(param1, param2) {
    // ...
}

The primary thing this is used for is automatic documentation generators. You run a program that scans your codebase, looks for these special comments, and automatically builds a set of documentation that you could, say, publish directly to a website. IDEs can also use them for tooltip popups. Generally, you want to write these like the reader won't have the actual code to read. Because they might not!

The second kind is standalone comments. They take up one or more lines all to themselves. I look at these like warning signs. When there's something about the upcoming chunk of code that doesn't tell the whole story obviously by itself. Perhaps something like:

/* The following code is written in a weird way on purpose.
I tried doing <obvious way>, but it causes a weird bug.
Please do not refactor it, it will break. */

Sometimes it's tempting to use a standalone comment to explain what dense, hard-to-read code is doing. But ideally, you'd want to shunt it off to a function named what it does instead, with a descriptive doc comment if you can't cram it all into a short name. Alternatively, rewrite the code to be less confusing. If you literally need the chunk of code to be in its confusing form, because a less confusing way doesn't exist or doesn't work, then this kind of comment explaining why is warranted.

The last kind are inline comments. More or less the same use case as above, the only difference being they appear on the same line as code, usually at the very end of the line:

dozen = 12 + 1; // one extra for the baker!

In my opinion, these comments have the least reason to exist. Needing one tends to be a signal of a code smell, where the real answer is just rewriting the code to be clearer. They're also a bit harder to spot, being shoved at the ends of lines. Especially true if you don't enforce maximum line length rules in your codebase. But that's mostly personal preference.

There's technically a fourth kind of comment: commented-out code. Where you select a chunk of code and convert it to a comment to "soft-delete" it, just in case you may want it later. I highly recommend against this. This is what version control software like Git is for. If you need it again, just roll back to it. Don't leave it to rot in your codebase taking up space in your editor and being an eyesore.

[-] TheDoctor@hexbear.net 7 points 1 week ago* (last edited 1 week ago)
dozen = 12 + 1; // one extra for the baker!

I got mad at this when I first saw it but then I remembered there’s some code at work that defines an hour as 50 minutes

pain

load more comments (1 replies)
[-] flashgnash@lemm.ee 18 points 1 week ago* (last edited 1 week ago)

"tells the user the current time" would be an excellent comment for a clock

I'm not the best at commenting my code, but generally I just try to think of what information I'd want to know if looking at this 10 years from now

Imo comments are best used sparingly, don't bother commenting something that anyone with a basic understanding of programming would understand straight away by reading the code

Functions should generally be commented with what parameters are and what they're for, plus what they output

use reqwest::Client;

// create a http client class that all other files can import 
// so as to only create one instance globally 

pub struct HttpClient {
    client: Client,

}
impl HttpClient {
        pub fn new() -> Self {
            HttpClient {
                client: Client::new(),
            }
        }

        pub fn client(&self) -> &Client {
            &self.client

        }

}

Here's an example where if I were to stumble onto this file 10 years from now, I might think wtf is this looking at it out of context, the comment explains why it exists and what it's used for

(we'll ignore the fact I totally didn't just add this comment because I suck at commenting personal projects)

[-] TheDoctor@hexbear.net 14 points 1 week ago* (last edited 1 week ago)

I often use comments as ways to say, “I know this is cursed, but here’s why the obvious solution won’t work.” Like so:

/**
 * The column on this table is badly named, but
 * renaming it is going to require an audit of our
 * db instances because we used to create them
 * by hand and there are some inconsistencies
 * that referential integrity breaks. This method
 * just does some basic checks and translates the
 * model’s property to be more understandable.
 * See [#27267] for more info.
 */

Edit: to answer your question more directly, the “why not what” advice is more about the intent of whether to write a comment or not in the first place rather than rephrasing the existing “what” style comments. What code is doing should be clear based on names of variables and functions. Why it’s doing that may be unclear, which is why you would write a comment.

[-] jbrains@sh.itjust.works 11 points 1 week ago

Write comments that explain why the code isn't obvious just by reading it. Why did you do things the long way? What did you need to work around? Why didn't you do the thing that anyone reading the code would expect you to do?

Also write comments that explain the purpose of the functions you use, in case the names of those functions don't make it clear on their own.

[-] Dunstabzugshaubitze@feddit.org 10 points 1 week ago

the "what" is interesting on interfaces or when you generate documentation with some tool like sphinx or javadoc.

the "why" is interesting when you are somewhere inside a class or function and do something in a "strange" way, to work around a quirk in the codebase or something like that, or when you employ optimizations that make the code harder to read or atleast less obvious why somethings are done.

[-] marlowe221@lemmy.world 8 points 1 week ago

“Why” comments make more sense as application complexity grows.

You also have to consider interaction of the code with other external systems - sometimes external APIs force you to write code in ways you might not otherwise and it’s good to leave a trail for others on your team (and your future self…) about what was going on there.

load more comments (3 replies)
load more comments (14 replies)
[-] lnxtx@feddit.nl 21 points 1 week ago

Self-explainable, when you aren't writing spaghetti Perl scripts.

[-] Swedneck@discuss.tchncs.de 18 points 1 week ago* (last edited 1 week ago)

//forgive my sins, it took me 2 hours to nail down this arcane spell. if anyone touches this they will know my wrath
=(/&)((//((%=)(&)%)(&()

load more comments (3 replies)
[-] some_guy@lemmy.sdf.org 21 points 1 week ago* (last edited 1 week ago)

Checked one of mine:

# get path to the download directory

Oh, ok.

[-] darkpanda@lemmy.ca 24 points 1 week ago

The code directly below:

function getPathToUploadDirectory() {
  return config.tmp_path
}
load more comments (1 replies)
[-] Underwaterbob@lemm.ee 15 points 1 week ago

I like to include profanity in all my comments for spiciness.

[-] ouRKaoS@lemmy.today 10 points 1 week ago

"I don't know why, but if you remove this comment it fucks up everything."

I saw this comment in a piece of code once; I left it there as not to tempt the fates.

load more comments (1 replies)
load more comments (1 replies)
[-] figaro@lemdro.id 9 points 1 week ago

Made a comment

[-] GooberEar@lemmy.wtf 8 points 1 week ago

I know some folks are joking about and dunking on this, but in modern times, I have justification. Call me lazy, but I have found myself writing out these comments and then letting the AI take over to at least give me a sketch of an implementation. Works reasonably well and saves me a lot of time and effort. Mostly I don't bother to remove them, though I usually edit them a bit.

On the other hand, there are factions within my colleagues who steadfastly insist that commenting is unnecessary and to some degree even potentially harmful, and that if you feel the need to comment your code, it means your code should be improved so that it's obvious what it is doing without the need for comments.

[-] theherk@lemmy.world 13 points 1 week ago

And your colleagues are probably correct with respect to this sort of «what it does» commenting. That can be counterproductive because if the code changes and the comment isn’t updated accordingly, it can be ambiguous. Better have the code be the singular source of truth. However, «why it does it» comments are another story and usually accepted by most as helpful.

load more comments (3 replies)
load more comments (4 replies)
[-] TootSweet@lemmy.world 7 points 1 week ago

We have to go deeper.

[-] linkhidalgogato@lemmy.ml 7 points 1 week ago

basically how it feel when a professor requires u comment every single line of code u write to explain it. I know people tend to drop out of real engineering to do programing but an entire 4 years of this bullshit as opposed to just a couple classes sounds way worse than calc 3 or differential equations.

[-] Urist@lemmy.ml 1 points 6 days ago* (last edited 6 days ago)

The only problem with courses like calc 3 and differential equations (in my experience, as a mathematician) is that they are cheating somewhat. By cheating I mean relying on inadequate, flawed or entirely omitted proofs. How can the students truly understand something if they are not presented the whole story (or at least reference)?

The good thing about these courses are that there are usually no shortage of relevant exercises!

[-] linkhidalgogato@lemmy.ml 1 points 6 days ago

u could be right calc 3 was alright, pretty fun actually but differential equations i still dont get at all, maybe i should try learn it on my own now with more time and no pressure.

[-] Urist@lemmy.ml 1 points 6 days ago

I detested differential equations. However, that was more due to how it was presented than the underlying, surprisingly, beautiful math.

[-] style99@lemm.ee 7 points 1 week ago

A true Klingon never uses comments.

load more comments (1 replies)
load more comments
view more: next ›
this post was submitted on 28 Sep 2024
1178 points (99.2% liked)

Programmer Humor

32197 readers
649 users here now

Post funny things about programming here! (Or just rant about your favourite programming language.)

Rules:

founded 5 years ago
MODERATORS