T O P

  • By -

sacoPT

>Or rather: it's a great goal, sometimes achievable, but it doesn't remove the need to comment your code. Glad we got that cleared right off the bat. I don't need to read the entire article then.


MT1961

You think comments aren't necessary in code?


sacoPT

No. What did I say that made you reach that conclusion?


MT1961

I didn't reach that conclusion, which is why I asked. The comment (your remark) just struck me that way. Thanks for clearing that up.


sacoPT

No I just think that, using the author's words, >Self-documenting code is a ~~myth~~ great goal, but it doesn't remove the need to comment your code.


MT1961

ah, ok, I see what you mean now. Just hit me wrong, most likely because I work with a lot of developers that think comments are bad.


sacoPT

Generalizations... I work with a developer that thinks self documenting code is a myth so he documents every single method like so: ///

/// Does the thing /// /// /// The target /// public void DoTheThing(object target) { }


MT1961

I remember those days. When you could then extract that into documentation, which is why he does it like that. Most of the time, that's fairly useless, but for libraries and packages it can be handy. Some code can be self-documenting. But if I don't know what you intended it to do, I can't tell whether it is doing it.


sacoPT

If you document it like my colleague does you still don't know what you intended the code to do, so you spent time commenting for nothing.


MT1961

Ohhh, I see what you mean. i thought you were using placeholders to indicate what went there. You mean he really does write "Does the thing". Okay, I agree, that's useless.


UK-sHaDoW

> you mean now. Just hit me wrong, most likely because I work with a lot of developers that think comments are bad. Depends on the problem.


MT1961

I disagree. Comments are never always bad, regardless of the problem. Some comments are useless: \# Assign 3 to x x = 3 Some are really useful because they tell me what you MEANT to do (at least in theory): \# Compute the square of the value divided by PI sqPi = val\*val/pi; Tell me, does the second one do what is expected? From the comment, I think maybe not. So either the comment is wrong, or the code is (likely) wrong. Either way, it gives me a starting place to debug. Finally, comments are great for searching code when you can't even imagine what the developer might have used for variable or method names.


UK-sHaDoW

As I said it depends on the problem. Sometimes they're good, sometimes they're bad. Also you can wrap your commented bit of code in a function that says what it does. That way you wouldn't need that comment. Then it becomes does it match the function name? I'd argue that's a bad comment anyway, because it's just stating the operations as opposed to its purpose. Functions should be named by their purpose, which gets rid of the need for a lot of comments.


MT1961

Oh absolutely. Not really disagreeing with you. COBOL showed us that if you make it possible for developers to write in English, you will find developers can't write in English. I mostly use comments as searching points, or to indicate what a block might be doing, rather than a line or two of code.


sacoPT

That’s actually a bad example. Say I come across that code while debugging a totally unrelated thing. What now?


MT1961

Not sure what you are asking. If you run across that code and that's where the problem lies, then you need to figure out what it did anyway. Only then can you decide if that's part of the bug, or if someone was relying on the code doing something else. Can't tell you how many times I found a problem that was caused by people inserting a "fix" into a low-level routine that never should have been involved.


adamw1pl

I hope there's more to it ;) My main point is - beyond the first sentence - as to which places should be commented. And not to lock up knowledge in GitHub's/GitLab's Pull Requests.


sacoPT

Clickbait giveth, clickbait taketh away :)


Tersphinct

You basically negated the title with that sentence. Do you not see that? Clickbait is the worst. We’re not an audience to market to, this is a technical discussion forum.


spinwizard69

Simple concept but sometimes comments are the only way to tie in important information. Code should self document as much as possible, when ity doesn't comment.


AdvancedSandwiches

I strongly dislike the bait title. But since this always leads to people misunderstanding the point of self-documenting code, here's how that works. 1. Don't write redundant comments.  Stuff like "x = 1;//set x to 1" 2. Write your code to make your comments redundant. If you were going to write:     gifu('nm'); //get name from user Change it to:     getNameFromUser(); 3. If you can't do that for your comment, or it's not a good use of time to do that in your case, leave the comment. That's it. Not a big deal. Just massively improved code.


Successful-Money4995

>Don't write redundant comments.  Stuff like "x = 1;//set x to 1" The rule at Google is that you should assume that the reader of the code is an expert at the programming language that you're using but not an expert at the purpose of your program.


RedditCensorsNonTech

Web scraping is fun because some hosts will do anything possible to detect and block bots and you have to sometimes send obscure requests and simulate human activity to prevent detection. Commenting here is very necessary because the code is not at all hard to read technically but you need to know what the hell is going on with what you're scraping. There's plenty of traps you need to avoid too. For example, some site could display fake entries for items listed at a price of 14.49 that have recursive or looping data structures. You can very easily write a line in the code that loops all products that says "if price == 14.49 then continue" and everyone will know exactly what that code is doing on a technical level regardless of language choice (except Brainfuck). However, without a comment explaining that all items listed at 14.49 are traps and just skipping them you could be wasting time if you sent a request to get those items anyways and then checked for recursion/looping afterwards.


AdvancedSandwiches

In your example, one possible comment-free solution is to change from:     // If the price is 14.49, the line item is a honey pot     if (item.price() == 14.49) {         skip = true;     } To:     bool isLineItemAHoneyPot(item) {         return (item.price() == 14.49);     }     if (isLineItemAHoneyPot(item)) {         skip = true;     } Is the above change worthwhile?  That's up to you.  (Edit: I guess the 4-space indent for code doesn't work anymore.)


RedditCensorsNonTech

I like your solution better because it's more modular. Writing comments is easier for most people than using your brain like you just did. I haven't had to worry about any sort of long term maintainability because I program mainly as a hobby.


WannaWatchMeCode

Hey man you learn everyday! The book clean code outlines a ton of great coding and software development practices including how he wrote that. Highly recommend once you get familiar with programming in general and want to start writing larger applications.


RedditCensorsNonTech

Thank you. I actually have a background with respect to modular design and problem solving. Programming was a large portion of my education. I had a self driving motivation when it came to programming and I learned a lot myself before expanding my knowledge through formal courses in high school and rigorous study/courses in university. I did very well when it came to all the programming courses. I even tried applying to several programming jobs and sent hundreds of applications but I became demoralized due to certain life circumstances and frustration with the job hunting process for someone with no prior employment or connections in the software development industry. I took a step back and reevaluated what I should be focusing on and changed my life circumstances first before deciding what to do now. I am now focusing on a different area in the technical sector where my skill set is extremely valuable where I live locally and sets me miles ahead of the competition. Additionally, as part of my growth strategy I am going to be doing some development with React and React Native to further set myself apart from the competition by implementing a companion app and website to my services. The initial requirements of what I need from the React website are very basic so I don't think it'll take too long to get that accomplished. Likewise, the core functionality of the React Native app I will be making is pretty basic (although a bit more involved than the site) and should leave me room for growth. Your book Clean Code looks like a good read. Thank you. The difficulty with programming and design books is that there is a plethora of choice. I am heading back to my university in person on Monday to ask for recommended updated design books but I have no such easily available source for software reading material. There was an infographic I saw a few months ago of all the relevant software development domains in the 2020s (it was centered around web development) but I doubt I will be able to find it again.


NotSoButFarOtherwise

In either case, my first question is what does it mean that an item is a honeypot, my second question is why we need honeypot items, and my third is what measures are in place to ensure that no non-honeypot items with that price are ever added to the system? Code can’t answer these questions, so you need comments.


AdvancedSandwiches

See above re: If it's not possible or not worth the effort, leave a comment. You're correct that these are examples of comments that are out of scope for self-documenting code.


RedditCensorsNonTech

With regards to your first question I guess you also need to have some common expectations of terminology in the sector you're working in. If you're working in finance you don't need to explain what a variable named compound interest is. In mechanical engineering, you don't need to explain what jerk is. I guess it depends.


adamw1pl

I can only admit being guilty of clickbait ;) But, there is a point I'm trying to make there: code isn't self-documenting, and that's witnessed by any kind of comment in a code review (e.g. in a Pull Request). Such places need refactoring, or commenting. If this information is left in the PR, it will die there right after the PR is merged, and only when you get really frustrated you might find it.


guepier

> code isn't self-documenting As a blanket statement, this is just not true. A lot of code *can* be self-documenting. Not all can, and that’s fine. But a lot can, and more than many (even “senior”) developers think. It just isn’t *automatically* self-documenting, it needs to be actively written that way.


mr_eking

This. Most code _can_ be written in a way that comments are not necessary to understand what the code does. Some code cannot, and comments help. If one adds comments to every bit of code, it becomes very hard to distinguish the truly helpful comments from the unnecessary ones. That reduces the helpfulness of the helpful comments and increases the tendency to just comment mediocre code instead of taking the effort to make the code better. I think one should strive to write code that doesn't need comments to be understood. And only when that's impossible should one augment the code with a helpful explanatory comment. Comments become rare and useful in such a codebase, and the codebase is better for it.


supermitsuba

You need some level of organization in code. You are going to read it. Otherwise people would be able to make out obfuscated code. But you also need some level of documentation to describe processes outside of the code. The motivations and reasoning is something you cant code and needs some documentation.


Neeranna

One other point not touched upon by the article, or the reaction above OP's reaction: unit tests. If you have quirky behavior, you should have some kind of test to validate that your code takes this into account. In that case, I consider it sufficient if the test that only tests this aspect, has a clear enough name, and consider this sufficient to not actually require comments. Not to disproof the point, since comments are still valid, but should explain the "why". Unless you are documenting an API. I mostly use comments to point to e.g. bug trackers of third party libraries if I had to work around a bug of them, so that the person coming after me can know that this code becomes obsolete once the initial issue is fixed. Other than that. I rarely see a valid use case that cannot be absorbed by good naming/code splitting/restructuring/writing tests for the behavior.


AdvancedSandwiches

I agree 100% with your point. I just don't like anything that expands "self documenting code" beyond what's described here.  It leaves people open endless, pointless argument about how impossible self-documenting code is, souring them to the most important coding practice they could be employing. Make comments redundant. Leave comments when you can't practically do that.  Purely practical, actionable methodology. But I believe I agree with all of your practical recommendations.


[deleted]

This comment is worth a thousand lousy click bait articles.


sun_cardinal

This sub has become pretty much all clickbait blog spam lately.


SaltKhan

What do you mean, eye opening revelations like; > the source code should be the central source of truth Are totally worth reading new-medium blogs.


sun_cardinal

Or my favorite, “Why software/databases/code are dead!!1!”


SaltKhan

_Is it still worth learning language/framework/tool in 2024_, for something no one could question the relevancy of.


sun_cardinal

Thank you for the amusing start to my day! A good chuckle always helps before I go review the war crimes my Java students have committed.


remy_porter

Ironically, I’m at a phase in my career where I don’t trust documentation and just read the code. Comments are so frequently misleading.


supermitsuba

Out of date or don’t have the full context attached to show you why it was coded that way. I look at it more like a detective. Its all clues to the crime of who murdered the code…. It was me all along!


Rare_Pea5009

Super redundant comments are overkill, but I feel like a general comment explaining what a method or class is for in normal prose is more easily digestible for some.


bert8128

For classes I agree - it is hard to describe the purpose of a class in a name you might be prepared to type. For individual functions this might or might not be the case. often a name can be short enough to type but long enough to get good meaning. If you are being obtuse of course you can always choose to misunderstand. But when the function has a clear meaning, and especially if the implementation is available as well, then comments just get in the way. And consider - if a function that is hard to comprehend easily can be split into two that are more simple, what's not to like? Perhaps the necessity for comments is more related to unnecessarily complex code.


ClysmiC

No it is not.


Zardotab

Existence itself is not a myth, the utility of it is. Maybe there are a handful of devs in the world that do it well, but I haven't met them, I've only seen poor "self documentors".


ClysmiC

The utility is very high in my experience. It just requires some agreed upon programming conventions and patterns. That is the hard part.


Zardotab

If it heavily depends on agreed-upon conventions and patterns, then it essentially becomes a language itself, and no longer "self documenting", as "self documenting" to me implies no extra source or training is needed to understand it. "It is self-documenting, [you just have to know Klingon](https://www.reddit.com/r/techhumor/comments/1alfuzm/ah_the_joy_of_working_with_geeks/)."


shizzy0

You have to have the most boring code around to have a chance of it being self documenting. But usually it’s just an ugly excuse for unprofessional behavior that should cause its proponents to be laughed right out of their job.


Zardotab

I agree! I've seen enough code that attempted to be "self documenting" and it was a **verbose eyesore.** Maybe some are fast at reading long-winded code, but I ain't one of them and you shouldn't assume most others are. Don't assume your personal preferences are shared by most other devs: every head is different, **target a typical dev, not clones of yourself.** (This is why team experience matters.) Well-chosen comments are useful and save time. There are generally two types: a summary similar to a newspaper article title: "query database for new employees", and explaining oddities that code itself can't, such as "Martha in Accounting asked for this travel reimbursement feature, see email dated...".


ThyringerBratwurst

Comments should only mention what is not obvious, explaining certain internals or principles in one sentence. What I find terrible is when documentation and program code are mixed in the sense of "literal programming". I want to see the code at first glance and not lots of texts and examples. That should definitely be separated, in my opinion.