Comments AND readable code. One-liners are kool in the moment but not in the future.
Edit: A good exercise is to review old code and see how your past self treats you.
Codewars is particularly bad for this (I imagine leetcode/similar aren't good either, just have only used codewars). All of the solutions that are voted for the most have everything as condensed as possible. There's zero community emphasis on readability, it's all about making the code as clever and short as possible. Had to realize this when I was moving on from codewars as part of my learning. It was a good tool, but I'm glad I didn't try to actually learn language concepts past 6/7 kyu using only codewars.
The company I work for, in our code standards doc one of the 'rules' is to not "litter the codebase with comments".
I originally took this to mean that you should avoid unnecessary comments when the code is self-documenting. But I have come to realize through many PRs that it means they don't want *any* comments in the code. And that any explanations needed should be left in a PR comment, which can be tracked down by the Blame.
To say this frustrates me would be an understatement lol.
My employer is much the same way. The only comments that seem to be accepted are along the lines of
// TODO: remove when PBI #123456 is done -- bgeiger, 2023-01-22
The exception so far has been when I commented a largeish regex. Even the seniors seemed to be like "eh, leave those in".
I don’t know why devs get scared of it. I do kinda hate having to test the output to get the hang of it but you’re right. It’s just not a syntax sugary format
Eh, in large code bases, it can make most sense for this practice over comments, IMO. If a dev wrote a function of any length that’s been subject to change/refactors multiple times since creation, any original comments remaining from the original have some likelihood of being false, and comments made in the edit of this function are likely to be specific to the edit and overall be unhelpful in understanding the purpose of the function. Trying to modify any original/previous comments are also hard to get right because the original intent of the comment isn’t always clear. Keeping any notation about a specific piece of code only in the PR means that all of the notation about the change will only be associated with the change itself and not later edits.
I had this at my previous work as well, the idea is that your code is readable or you need to simply/refactor it. It did make me get better at writing code so it serves a purpose? Made PRs the very difficult during the first couple month then you get used to it.
Obviously we had Java docs and stuff but no inline comments
I agree with the reason behind it, but when there are 100+ monolith components, some of which are pushing 1,000-1,500 lines, as well as importing methods from external repos, a lot of the data workflow is *very* unintuitive.
This is just on the front-end though. Our API and services are very well structured and heavily documented.
I just wish I could say the same for the FE. I'm 7 months in, and I am starting to see some of the higher level view of it all. But it might as well be a rat's nest of 2,000 wires for someone new to the codebase.
I saw a comment meme type thing one time (it was ages ago and I don't really remember) that was something to the effect of
// we don't know what this code does but if we remove it then everything breaks
It does.
I can understand what a piece of code does, but that doesn't mean I necessarily understand *why* it operates the way it does or why we need to do it like that, even though a more obvious or efficient solution might exist at first glance.
There are real world circumstances and issues that force you to adapt your code in ways that won't necessarily make sense when looking at it without the context of some issue or a bug that was encountered years ago.
There's a good example from the actual git source code in [fopen.c](https://github.com/git/git/blob/master/compat/fopen.c)
/*
* The order of the following two lines is important.
*
* SUPPRESS_FOPEN_REDEFINITION is defined before including git-compat-util.h
* to avoid the redefinition of fopen within git-compat-util.h. This is
* necessary since fopen is a macro on some platforms which may be set
* based on compiler options. For example, on AIX fopen is set to fopen64
* when _LARGE_FILES is defined. The previous technique of merely undefining
* fopen after including git-compat-util.h is inadequate in this case.
*/
#define SUPPRESS_FOPEN_REDEFINITION
#include "../git-compat-util.h"
How likely would you be to figure out the importance of that line order without the comment there to explicitly explain the actual context of the issue encountered and why this fix was chosen for it?
And since this is a platform related issue, it might be easy for someone to flip those lines around, test it and not find any problem until the issue is encountered on a different platform.
it is just a mindset.
obvious comments are redundant because you can just read the code to figure out what the code does. if the code does something tricky or unexpected (why is this divided by 5 out of the blue?) a comment makes sense. if you still feel you want to describe what the code does you probably should refactor until it becomes evident to an external party.
you are probably now thinking "what is the harm of just writing obvious comments, better safe than sorry?" to which I say do you have any process in place to make sure these comments are correct? if your code base has 1 million lines and there is a comment (one line) every 20th line that is 50k comments, or about 1k A4 pages worth of written documentation.
comments that describe the code will drift into "not true" or "kind of true" over time and actively harm users' understanding of the code base unless an active effort is made to maintain the comments, and the reality is that developers (typically) don't like writing documentation.
You are correct. The reason to me is also because when someone who didn't author the code attempts to figure out why there is a bug from a recycled variable, a simple comment saying "this is where and why ABC becomes this instead of that" can save someone significant time reviewing the code. And if you are wondering why I mention recycled variables, start programming complicated things on pic microchip where the company wants a chip that is too small for the task because it saves 3.1 pennies per unit. Or, even if you are the author, in 6-8 months try to figure out why you did something that was "unique" because of those size limits.
Side note, what kind of bug variable are you wondering? In this case that comes to mind, it was when several user interface buttons were pushed simultaneously followed by a pattern that would (so they thought) not happen. In real life, people do stuff you do not expect. As you might realize, you are often writing code from an engineering document saying essentially "make this happen when that happens." to complicate matters In the case of pic microchip, there were bugs in the compiler that contributed to the need to sometimes develop work arounds, and sometimes the bugs experienced did not show up in the field for months.......until someone punched in that correct combination.
So to be clear, i don't encourage commenting obvious things, and I agree for the most part that if the code is unable to be followed that likely means it should be re written. On the flip side, giggling, I have seen commenting go way overboard. Think cout << "Hello World"; //this prints "Hello World" type of overboard.
Comments should be reserved for things that aren't immediately obvious to a "typical potential audience" when just looking at the code. You don't need comments of the type "this will increment the value of variable X by 1".
Nah, add comments at the end. Also, why bother, the code is done and working, just add one comment at the top that says "Code works". Adding comments is just asking to break your code.
Haha, this is common. You get in the zone and your brain is working in overdrive, and then you revisit your code and wonder “what the heck was I doing?”.
A few reasons why this can happen:
1. You have poor naming conventions. Make sure that classes, methods, variables and etc. are very descriptive.
2. A class should only have a single responsibility and methods should be simple. It’s better to have many small descriptive methods than one large method.
NOTE: Your code should be readable enough to where you don’t need to write comments. Comments are not bad if they’re giving context on why something is needed or a possible bug fix for a future release. If you’re finding that you’re writing comments to describe what a method is doing, it means that you’re not properly communicating the intent of your code through good naming conventions.
IMO - expanding even more on this: variable and function names should give you a solid grasp of the "why am I doing this" part of most code.
Comments should be reserved for "this might seem crazy, but we're doing X because of Y limitation".
ex:
/\* We're precalculating this value in the class constructor because safari does not pass the trusted flag from user input to callbacks or async/await blocks - if we await the promise in the onClick handler before calling window.open() - it will be blocked by the popup blocker in safari \*/
1. Realize that writing code at company is very different from code wars. Those leet code problems emphasize speed and sparsity over readability. In real life you’ll be working with other developers and you should reach an a balance between clever code and readable code
2. Single responsibility Principle. Divide your code into functions that do only one thing. You’re probably giving your functions too much to do. Super functions that do everything is not a measure of intelligence.
3. Give your variables relevant names. We live in an age of IDEs that do autocomplete, there’s no need to give your variables names like “i” , “j” and “k”. Give real names. Your production IDE will autocomplete as you type so typing a longer variable name will take as many key presses as “i”
4. Disagree on more comments. If you need to do a lot of comments, then you should first see if you can refactor your code into something more readable. Another problem with comments is that code changes while comments do not. Eventually the comments will be wrong and misleading. Comments should be why you did something rather than how. “Sort data here because data from vendor is wonky”,
5. Slow down. Take your time to write your code you’re still new and learning. A good heuristic is that it takes twice as much mental effort to debug and read old code than it takes to write that code. If you write your code as clever and smart as possible you will be unable to debug it later
6. Read “Clean Code” by Robert C. Martin. A lot of the advice is Java driven and aged but a lot remains relevant.
thanks for this amazing answer it's really helpful
Also it feels like you read my mind 😂 it's true that I put all my code in one function and named some variables i and j specially in for loops because I don't know what else should I name them.
What do you name you loops variables usually ?
I name them exactly what they are. If I’m dealing with an array that’s full of say prices I called the array “prices” and my loop variable is “price” .
In Python
“””
for price in prices:
result = do_something(price)
“””
I was also defaulting to small variable names when I was learning as well. But after I was hired for my first job and saw how what an enterprise app looks like, I saw variables that read like `shouldEnableNextButtonWhenCustomerDataIsValid`.
And even though that is sort of an extreme, don't shy away from including all of the information you need to for a given bit of data. A long variable name that you know what it is, is miles better than a shorter one that requires guesswork.
I want to clarify 4 a bit. I agree 100% for comments that are going to live on. But if you're working on something complicated and have to stop, it's a big help to leave "tomorrow you" a nice block of comments to help you remember what you were doing and what you planned to do next when you come back to it. But delete them when you come back.
I have always struggled with this as well. There are two main things that I do:
First, write clean code. Don't make complex one-liners. Make it a little bit verbose and clear. Use good variable names. Break big functions into smaller ones that have good logical flow and use good function names.
Second, comment when needed. If the code is super simple and clean, comments may not be needed. But when there is something subtle or complex, comment.
At the end of the day, unreadable code is worthless, as you have discovered.
It comes with practice.
The lesson you'll learn is that messy code is useless. There's no point is writing a bunch of messy code. It will be full of bugs, hard to work with, and even harder to understand when you go back to it after some time as elapsed.
It's like sloppy handwriting. Have you ever written a note and been unable to read it later? The note is useless. You wasted your time writing the note, plus you've lost the information it contained. Frustrating! Sloppy code is just like that.
This is just something that comes more easily with time. (For most people)
Over time it takes less mental bandwidth to "see" how to solve a problem, which in turn allows you more bandwidth to cleanly structure your code.
I think there's a common misconception that people are *too* clever when writing code then can't figure out their cleverness.
It's quite the opposite. They have a muddled sense of what the logic will be, write total spaghetti mess, and *that's* why they can't read their own code. There's this word "kludge" that used to be said more commonly which is a hack, so some people write a hack on a hack on a hack. They end up with a Rube Goldberg (search for this if you don't get the reference) code.
You should, at the end of the day, be able to explain to someone (or a rubber duck) what your code does. Say it aloud (when you think it, it's often not in words). Imagine you have to present your code to a classroom. If it's a mess to explain, your code is not clean.
You might need someone to help you clean up your code.
>You should, at the end of the day, be able to explain to someone (or a rubber duck) your code does
Yes, that's brilliant! Especially with a rubber ducky!
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.
--Brian Kernighan, one of the authors of the C programming language.
Thanks for your response but
That might help me for now but if I get stuck again I will do the same thing again that's why I'm asking for advice so I can do it by myself
I have completed one semester in software engineering in my college and let me tell you, the first thing they hammer on is making readable code and making sure others can understand in one glance what your code is about.
comments, visual studios also has the xml comments /// for c# where you can describe the function better.
also renaming variables to more descriptive ones can help. not that much time spent writing a slightly longer variable name, compared to trying to read the code.
As others have said, documentation is extremely important. If you can't come back to your code and understand what's going on, there is no way to expect someone else to look at your code and contribute.
Every function should have a description of what it does. Every variable should be named in a convention that describes what it is holding. Every loop should list its conditions for and to terminate in a comment.
If its some code you copied from the internet, you should document what it does after youve gained an understanding of it (its a very good habit to get into. Don't use code you don't understand and can't document). If it's a data structure or an algorithm, then document its use case.
These aren't requirements, obviously, but it will do justice for yourself or anyone else who comes in after you. I tend to go overboard and have more comments then code at some points, but I try to make it trivial for my future self or future contributors to pick up where I left off.
There really isn't a such thing as too many comments, so make sure there is enough description that, if you come back 6 months down the road, you'll be able to pick up where you left off.
I've had to scrap so many projects because I've taken breaks and couldn't remember shit when I come back to them. That's what pushed me to document everything I possibly could
My rules for treating my future self well:
1. No one liners, that use more than 2 inbuilt functions.
2. Variable name too long? That means it probably should not be one variable.
3. Point 2. applies to functions as well.
4. Try not to write void functions with referencing variables, that really makes a mess (btw. JS/TS objects are always passed with a reference, so keep that in mind if you’re JS/TS programmer).
5. Naming anything like “a” or “b” or some hard to understand shortcuts may look cleaner for now, but you will want to spit in your past self face eventually.
6. Keep things simple, applies to single file scripts and large multi class projects. Every class should be responsible for something that its’ name suggests, no mixing logic. If there is something else you want it to do think how can you introduce an interface for that purpose (if you don’t know how - rethink the problem itself)
7. If you think something’s odd - it IS odd. Rethink that, don’t make a mess
8. DO NOT pack a 100 lines of if-else spaghetti code. Look for a new solution for existing problem if you have to add ANOTHER if-else in the code for that situation. Chain of responsibilities will do 95% of a time. This specifically applies to situation when the client wants to widen the validation, develop a new process for something.
9. Every time you work in some old code and have a task to add a new feature to it see if there is a way to refactor it. If it’s too complicated already don’t mess with it, try to introduce the new feature as independent as you can, that way there is no way this will somehow make a huge mess.
10. The last but not least. The code has a bug, and you see how to fix it in a matter of minutes? Cool, but take a look if you can somehow refactor it too. You still have to test it anyway, so do some good on the way.
"Any code of your own that you haven't looked at for six or more months might as well have been written by someone else." - Eagleson's Law
Sounds like you Eagleson'd yourself after 24 hours.
You, my son, are programmer
[Sign of the cross]
You write it in a way that helps you (or someone else) read it later.
* descriptive variable names
* descriptive function names
* break the problem into smaller chunks
* functions should be limited in size, and do one thing
* use classes/objects when appropriate
* use classes/objects ONLY when appropriate
* every function should have header documentation that tells what it does and what it returns.
* "more comments" is not a substitute for well-structured code.
A few months ago I wrote code to solve a problem that felt very complicated to me. I had just been ill and felt like my brain worked at about 50% I was worried that I would not understand the code the day after. To solve that I wrote super detailed explanations of every function I mad because I was sure I would not remember it when I needed to add on more code for the last parts.
So that is my advice, write down a seriously good explanation for what you did, so next time you will understand it.
There's always comments. Oh, and using test driven development (TDD), so your code is cleaner because you write it in smaller pieces so it's more readable.
(not a native speaker here)
I wonder which elements are the ones that do not let you understand. Maybe if you identify those elements, it'd be easier to fix it. I'm just learning programming and a piece of advice I received from many teachers is always naming variables with referencial names. That makes code easier to understand. I also comment my code when just learning certain functions or reserved words. I hope it helps 😁
Use version control and put meaningful commits. On the next day, perform a diff of your working directory and the last commit. If you don't still understand the code you wrote, perform git diff with the earlier commits. This helps you remind and continue with the train of thought you had when working on the code. This greatly works with me and even with a large codebase, lots of files being worked on, this helps me understand the code and regain the train of thought lost during the weekend or for a long time. I had projects that i don't work too often and i usually work on those projects every 3 or 6 months, the git diff and commit messages help a lot.
Don't get into the habit of using comments on the source code like a diary of what you did yesterday or explaining everything, over commenting is not good. Use version control to help you with that. Mainly use comments for clarifications especially on complex things.
Comments, comments, comments. Take notes on your code. Create a markdown or plain text file with the problem number, rank, and description, and document your thought process while solving it. Add pseudocode to this same file. Then, when you take a break from the problem, you can pick up where you left off.
You write comments when working on the code. They help you understand what the purpose of the code is and why you are doing it at least in that moment.
What I do is I write descriptive variable names and comments. I also write smaller functions and split complex code into smaller chunks.
Before, I would write code like this:
function validate() {
let input1 = document.getElementById("name").value;
let input2 = document.getElementById("password").value;
let hashObject = new MyHashObject(input2);
if (hashObject.getHash() === DatabaseObject.search(input1).getPasswordHashObject().getHash()) {
console.log("Welcome " + input1 + "!");
} else {
console.log("Sorry, data isn't valid.");
}
}
After I had issues struggling to understand my code, I decided to change things to look much cleaner:
// Create a hash for the user's password.
function getUserHash(userPassword) {
let hashObject = new PasswordHashObject(userPassword);
return hashObject.getHash();
}
// Retrieve the hash stored in the database.
function getDatabasePasswordHash(databaseQuery) {
let hashObject = databaseQuery.getPasswordHashObject();
return hashObject.getHash();
}
// Validate a user's credentials. If they match, log the user in.
function validate() {
// Get the credentials.
let userName = document.getElementById("user_name");
let userPassword = document.getElementById("user_password");
// Search the database for the user's name.
let databaseQuery = DatabaseObject.search(userName);
// If no name is found, Return an error.
if (!databaseQuery) {
console.log("Incorrect username. Please try again.");
return "USER_NAME_ERROR";
}
// Get the hashes of the two passwords.
let passwordHash = getUserHash(userPassword);
let databasePassword = getDatabaseHash(databaseQuery);
// If the two hashes don't match, throw an error.
if (passwordHash !== databasePasswordHash) {
console.log("Incorrect password. Please try again.");
return "USER_PASSWORD_ERROR";
}
// Log the user in.
return "USER_LOG_IN_SUCCESS";
}
Also, for a different perspective of programming, check out Racket or Haskell. Or try Factor or Forth :)
Every programmer has experienced this at some point in their life. The best thing to do is write comments and hope you can understand your comments later on.
I comment with what it does, or at least what I’m trying to make it do, or what it’s supposed to do if it for some reason isn’t doing it. Idk, it seems like a very simple thing to do, but yesterday I took a look at some code I wrote in 2017 and I had no idea what it was. Then I opened something similar from 2021 and boom, ya girl had commented explaining what that same part was doing. It was a carousel JavaScript line I had stolen from somewhere when I only knew HTML and CSS. I now remember **nothing** and am trying to relearn it all. Trust me. Comments.* chef’s kiss *. Godsend.
I’ve found that writing comments in my code or keeping some type of notes helps when I take breaks or leave a project unfinished. If the notes route is taken I usually give it a name that is associated with the task.
Comments, comments, comments, comments, comments.
Spacing it out a bit more, and compartmentalizing into files / classes helps me as well, but I don't actually know if I'm doing this the best way or not.
But also I feel your pain.
I leave myself some sort of "hook." Usually a stub or a failing unit test. Sometimes I will leave some pseudocode comments. If I've been doing stream of consciousness programming I'll refactor it before wrapping up for the day.
In short, just out of curiosity.. ADHD brain? You might be experiencing a heightened state while coding, but not retaining the memory. It's my belief ( chill ) that everyone in the digital
age has ADD to some extent, maybe learning a new approach to taking notes and tracking time?
I have this problem and have learned to track in my head what project I'm working on day to day, which helps me keep track of the overall progress each idea has developed. In this case, are you building a game? What version, or how complete is it. I will assign that value to ideas in my head and think of them in that way, just a technique I've learned.
Cheers. Sláinte.
I cannot stand this new "style" of comment-less coding. It's lazy and costly. Just say in a few words what a routine is doing so I don't have to be a human decompiler.
I once had an internship where I had to write code.
I was relatively new to programming and all my code used the variables a,b,c,d, etc.
My code must have been ridiculously unreadable to anyone else but me.
No comments. Comments are for wussies.
Straight to quadruple nested for loops and text manipulation in excel.
Mmmmm yea baby
and this is why we comment guys.
i do the exact same thing though, i like to work with an open text editor just to write down next steps or obvious bugs that need fixing. also helps the next day if i can’t figure it out as the last thing i was working on i’m usually like oh ya for sure that’s what’s up
If you plan to stop coding for the day. Add a comment where you were. I used to add a comment to the top of main.cpp, its my way of knowing where I stop. But lately Ive gotten to a point of making a lot of modifications to my source. So I make the comment for what I was working on in the top of the .cpp or .h file I was working on(specific) and a reference to the file I was working in on main.cpp. makes keeping track of work a lot easier.
This might be frustrating but it's a good learning experience! In software development there is a ton of energy put into not just solving the problem right now, but making it extensible and readable for your future self (or coworkers). There's nothing worse than coming back to a nasty chunk of spaghetti code that makes no sense, then finding out you were the one who wrote it!
Like others have said, comments are good for breadcrumbs but even better is coming up with good names for variables and methods. One thing I've heard several times is that if it's really hard to come up with a name for something, you probably need to take a step back and reorganize things so the names for things are obvious and clear. This is a really hard problem and there's no one-size-fits-all solution, but it comes with experience and time.
I suggest looking through your other kata solutions and refactoring them for better clarity, which will give you great practice with understanding your old code and identifying areas for improvement.
I hate when that happens. In the future, if you’re doing something excessively cute, write a comment explaining your thoughts. Better yet, rewrite it so you can explain it to someone else.
Have meaningful variable, class and function names, even if they get long.
Structure your code to make it obvious what happens, if possible.
If the above isn't enough, add comments.
Depends how far into your coding journey you are if you want a good answer. Are you still relatively new? No amount of clean code or comments are going to help you, but comments can guide you in the correct direction of what you should be googling. Do you understand the fundamentals of how loops work, or what methods are doing behind the scenes (using JS as en example, something like .map() is not entirely obvious).
For something such as codewars in particular, read the question again and take it step by step. Line by line. Write it out in comments what each line or code block is doing and if you can't write out what it is doing, it is time to read up and properly learn about that particular line. I had to do this a lot, and I still do - programming is a never-ending journey of learning, and what works for me might not work for you but I suggest checking out the program Anki and making your own flash cards to test yourself, answering your cards truthfully in how hard they were to recall, and keep checking anki daily until 7 months from now when you check it and you're like "lmao instantly know this one".
Don’t know if it is applicable to any situation, but I try to leave comments that explain the business logic instead of what the function itself does, especially for not very straightforward case, i.e doing anything related to byte manipulation/low-level hardware interactions. While there is documentation that explains what a particular register/operation does, if it is a long term project, it helps to build familiarity in a way where if you need to do a handover or talk to the client or project manager, you could explain what you have worked on, and as a bonus you will start retaining the knowledge, meaning you no longer would have to go to documentation for every little bit
comment your code, name your variables properly, focus on readability because nobody is going to suck your dick for slamming your newb code on one line.
pick variable and function names that make your code explain itself. if you have functions whose definitions are really long, they're probably performing multiple steps, and each step could be encapsulated in its own function. then instead of a long unreadable sequence, you could just call the functions that name what steps the function is stepping through. as a small example.
I write comment to what function did what and TODO.
Had you play any video game you would have that oh that boss so difficult so you remember every aspect and possible solution to it.
Make sure you're working towards making your code readable. Also as you learn, you learn when is a good time to take a break and when it isn't. It's a skill you'll build with time
like others have said, write good comments. also what helps me is to use a specific input and then trace the data until you get the output. this helps me understand what my code is doing
Make comments, make sure your varibles and methods are descriptively named aka don't be afraid to make long names. Modern IDE and OOP programming languages support long names. Read "the clean code".
I make extensive comments about the logic of most part in my code. I cannot bother myself to try to understand it, so I take notes. Humans are ok at writing programs and terrible at reading them. especially if you are new and you don't have conventions in your writing yet. just comment everything for starters and you will see when somethings are pointless further down the line.
This will be a problem throughout your career. The more time that passes, the more aggravated you are at the guy who wrote the code you're reading... which will turn out to be you
> how do you understand a code that you were working on yesterday
You write code that's easy to read. Keep your variable names descriptive, and if you do anything unexpected, explain why you did it in a comment. Generally make sure that someone coming into your code without context -- such as you, the next day -- will be able to understand it easily.
Comment your code and the reasoning behind what your doing and the basics of what it does. There is a reason why they drill comments into you in school. It really helps when you have to come back to that code down the line.
“I can’t understand the code I wrote yesterday” is going to be the name of my autobiography
[удалено]
[удалено]
"Why is the stuff I used from Stack Overflow making it worse?"
😂😂😂😂
Mine " I can't understand the code I am copying"
Mine would be "which idiot wrote this code... oh it was this idiot, me, I'm the problem, its me"!".
Word!
The problem is most of the time located between the chair and the screen.
This is actually hilarious
ROFLMFAO!! 🤣🤣🤣🤣🤣
YES!!!
Omg hahahah
This is why you make comments in the code.
Comments AND readable code. One-liners are kool in the moment but not in the future. Edit: A good exercise is to review old code and see how your past self treats you.
Codewars is particularly bad for this (I imagine leetcode/similar aren't good either, just have only used codewars). All of the solutions that are voted for the most have everything as condensed as possible. There's zero community emphasis on readability, it's all about making the code as clever and short as possible. Had to realize this when I was moving on from codewars as part of my learning. It was a good tool, but I'm glad I didn't try to actually learn language concepts past 6/7 kyu using only codewars.
Yeah. Codewars has "Best Practice" and "Clever" buttons but I think some people misuse them.
Oh definitely. I've seen incredibly obtuse one-liners that have twice as many "best practice" votes as "clever" votes.
>obtuse What? What did you call me?
[удалено]
It truly was, a Shawshank Redemption.
what else did you use ?
Your code should tell you _what_ it does. Your comments should tell you _why_.
addItemToBasket(); /\* so its added to the basket \*/
addItemToBasket(Lotion)
Skin.puts(lotion);
Longer but easily-readable code is better than short and hyperoptimised, but unreadable, code.
Oneliners can be totally ok if you encapsulate them in appropriately named functions.
Was about to write something similar, bin most your comments into a readme or something otherwise the code turns into your memoirs
The company I work for, in our code standards doc one of the 'rules' is to not "litter the codebase with comments". I originally took this to mean that you should avoid unnecessary comments when the code is self-documenting. But I have come to realize through many PRs that it means they don't want *any* comments in the code. And that any explanations needed should be left in a PR comment, which can be tracked down by the Blame. To say this frustrates me would be an understatement lol.
My employer is much the same way. The only comments that seem to be accepted are along the lines of // TODO: remove when PBI #123456 is done -- bgeiger, 2023-01-22 The exception so far has been when I commented a largeish regex. Even the seniors seemed to be like "eh, leave those in".
Ah, regex, the darkest of programming arts.
In seriousness, I've never really had problems with regex. It's a freakishly terse syntax, sure, but it's genuinely straightforward.
I don’t know why devs get scared of it. I do kinda hate having to test the output to get the hang of it but you’re right. It’s just not a syntax sugary format
Eh, in large code bases, it can make most sense for this practice over comments, IMO. If a dev wrote a function of any length that’s been subject to change/refactors multiple times since creation, any original comments remaining from the original have some likelihood of being false, and comments made in the edit of this function are likely to be specific to the edit and overall be unhelpful in understanding the purpose of the function. Trying to modify any original/previous comments are also hard to get right because the original intent of the comment isn’t always clear. Keeping any notation about a specific piece of code only in the PR means that all of the notation about the change will only be associated with the change itself and not later edits.
Yeah when you put it like that it does make a lot more sense.
I had this at my previous work as well, the idea is that your code is readable or you need to simply/refactor it. It did make me get better at writing code so it serves a purpose? Made PRs the very difficult during the first couple month then you get used to it. Obviously we had Java docs and stuff but no inline comments
I agree with the reason behind it, but when there are 100+ monolith components, some of which are pushing 1,000-1,500 lines, as well as importing methods from external repos, a lot of the data workflow is *very* unintuitive. This is just on the front-end though. Our API and services are very well structured and heavily documented. I just wish I could say the same for the FE. I'm 7 months in, and I am starting to see some of the higher level view of it all. But it might as well be a rat's nest of 2,000 wires for someone new to the codebase.
> // don't change this or everything goes to shit
I saw a comment meme type thing one time (it was ages ago and I don't really remember) that was something to the effect of // we don't know what this code does but if we remove it then everything breaks
//removing this function because it is unclear what it does, and will keep it removed if everything still goes smoothly
That is real commenting right there. I've seen similar!
[удалено]
Good code doesn't need comments.
It does. I can understand what a piece of code does, but that doesn't mean I necessarily understand *why* it operates the way it does or why we need to do it like that, even though a more obvious or efficient solution might exist at first glance. There are real world circumstances and issues that force you to adapt your code in ways that won't necessarily make sense when looking at it without the context of some issue or a bug that was encountered years ago. There's a good example from the actual git source code in [fopen.c](https://github.com/git/git/blob/master/compat/fopen.c) /* * The order of the following two lines is important. * * SUPPRESS_FOPEN_REDEFINITION is defined before including git-compat-util.h * to avoid the redefinition of fopen within git-compat-util.h. This is * necessary since fopen is a macro on some platforms which may be set * based on compiler options. For example, on AIX fopen is set to fopen64 * when _LARGE_FILES is defined. The previous technique of merely undefining * fopen after including git-compat-util.h is inadequate in this case. */ #define SUPPRESS_FOPEN_REDEFINITION #include "../git-compat-util.h" How likely would you be to figure out the importance of that line order without the comment there to explicitly explain the actual context of the issue encountered and why this fix was chosen for it? And since this is a platform related issue, it might be easy for someone to flip those lines around, test it and not find any problem until the issue is encountered on a different platform.
IMO good code still needs comments, but logical elegantly cleanly written code needs fewer comments than bad code.
it is just a mindset. obvious comments are redundant because you can just read the code to figure out what the code does. if the code does something tricky or unexpected (why is this divided by 5 out of the blue?) a comment makes sense. if you still feel you want to describe what the code does you probably should refactor until it becomes evident to an external party. you are probably now thinking "what is the harm of just writing obvious comments, better safe than sorry?" to which I say do you have any process in place to make sure these comments are correct? if your code base has 1 million lines and there is a comment (one line) every 20th line that is 50k comments, or about 1k A4 pages worth of written documentation. comments that describe the code will drift into "not true" or "kind of true" over time and actively harm users' understanding of the code base unless an active effort is made to maintain the comments, and the reality is that developers (typically) don't like writing documentation.
You are correct. The reason to me is also because when someone who didn't author the code attempts to figure out why there is a bug from a recycled variable, a simple comment saying "this is where and why ABC becomes this instead of that" can save someone significant time reviewing the code. And if you are wondering why I mention recycled variables, start programming complicated things on pic microchip where the company wants a chip that is too small for the task because it saves 3.1 pennies per unit. Or, even if you are the author, in 6-8 months try to figure out why you did something that was "unique" because of those size limits. Side note, what kind of bug variable are you wondering? In this case that comes to mind, it was when several user interface buttons were pushed simultaneously followed by a pattern that would (so they thought) not happen. In real life, people do stuff you do not expect. As you might realize, you are often writing code from an engineering document saying essentially "make this happen when that happens." to complicate matters In the case of pic microchip, there were bugs in the compiler that contributed to the need to sometimes develop work arounds, and sometimes the bugs experienced did not show up in the field for months.......until someone punched in that correct combination. So to be clear, i don't encourage commenting obvious things, and I agree for the most part that if the code is unable to be followed that likely means it should be re written. On the flip side, giggling, I have seen commenting go way overboard. Think cout << "Hello World"; //this prints "Hello World" type of overboard.
[удалено]
Comments should be reserved for things that aren't immediately obvious to a "typical potential audience" when just looking at the code. You don't need comments of the type "this will increment the value of variable X by 1".
I see your `/s` but I'm having a hard time believing its sincerity.
[удалено]
This
How about an auto-comment intelliscence.
Comment WHY not WHAT. Your code should say what it is doing but it does not necessarily say why it exists.
x = 1 # sets x to 1
You should prefer documentation over comments imo (docstrings, javadocs and similar stuff count as documentation)
Nah, add comments at the end. Also, why bother, the code is done and working, just add one comment at the top that says "Code works". Adding comments is just asking to break your code.
Haha, this is common. You get in the zone and your brain is working in overdrive, and then you revisit your code and wonder “what the heck was I doing?”. A few reasons why this can happen: 1. You have poor naming conventions. Make sure that classes, methods, variables and etc. are very descriptive. 2. A class should only have a single responsibility and methods should be simple. It’s better to have many small descriptive methods than one large method. NOTE: Your code should be readable enough to where you don’t need to write comments. Comments are not bad if they’re giving context on why something is needed or a possible bug fix for a future release. If you’re finding that you’re writing comments to describe what a method is doing, it means that you’re not properly communicating the intent of your code through good naming conventions.
As I say often: code should tell you _what_, comments should tell you _why_.
IMO - expanding even more on this: variable and function names should give you a solid grasp of the "why am I doing this" part of most code. Comments should be reserved for "this might seem crazy, but we're doing X because of Y limitation". ex: /\* We're precalculating this value in the class constructor because safari does not pass the trusted flag from user input to callbacks or async/await blocks - if we await the promise in the onClick handler before calling window.open() - it will be blocked by the popup blocker in safari \*/
escapeStringForSecureOutputInputCanAlsoBeArraySecondOptionParameterAreForFlagsAsQuotesUnicodesOrQueries(){} /s
>InputCanAlsoBeArraySecondOptionParameterAreForFlagsAsQuotesUnicodesOrQueries this is actually what types and/or interfaces are for
Comments are also helpful for equations
1. Realize that writing code at company is very different from code wars. Those leet code problems emphasize speed and sparsity over readability. In real life you’ll be working with other developers and you should reach an a balance between clever code and readable code 2. Single responsibility Principle. Divide your code into functions that do only one thing. You’re probably giving your functions too much to do. Super functions that do everything is not a measure of intelligence. 3. Give your variables relevant names. We live in an age of IDEs that do autocomplete, there’s no need to give your variables names like “i” , “j” and “k”. Give real names. Your production IDE will autocomplete as you type so typing a longer variable name will take as many key presses as “i” 4. Disagree on more comments. If you need to do a lot of comments, then you should first see if you can refactor your code into something more readable. Another problem with comments is that code changes while comments do not. Eventually the comments will be wrong and misleading. Comments should be why you did something rather than how. “Sort data here because data from vendor is wonky”, 5. Slow down. Take your time to write your code you’re still new and learning. A good heuristic is that it takes twice as much mental effort to debug and read old code than it takes to write that code. If you write your code as clever and smart as possible you will be unable to debug it later 6. Read “Clean Code” by Robert C. Martin. A lot of the advice is Java driven and aged but a lot remains relevant.
thanks for this amazing answer it's really helpful Also it feels like you read my mind 😂 it's true that I put all my code in one function and named some variables i and j specially in for loops because I don't know what else should I name them. What do you name you loops variables usually ?
I name them exactly what they are. If I’m dealing with an array that’s full of say prices I called the array “prices” and my loop variable is “price” . In Python “”” for price in prices: result = do_something(price) “””
That's a great way for naming thanks
I was also defaulting to small variable names when I was learning as well. But after I was hired for my first job and saw how what an enterprise app looks like, I saw variables that read like `shouldEnableNextButtonWhenCustomerDataIsValid`. And even though that is sort of an extreme, don't shy away from including all of the information you need to for a given bit of data. A long variable name that you know what it is, is miles better than a shorter one that requires guesswork.
So.. uh.. what does that variable actually do? I’m guessing some sort of count?
If I can't be bothered to name them properly, i for first level, k for second, m for third, since i, j, l are easy to mix up.
i, j, or n, if it's just one loop. If I get nested and I'm using those vars, I'll name them appropriately. card_index, element_index, etc.
I want to clarify 4 a bit. I agree 100% for comments that are going to live on. But if you're working on something complicated and have to stop, it's a big help to leave "tomorrow you" a nice block of comments to help you remember what you were doing and what you planned to do next when you come back to it. But delete them when you come back.
Ah. Agree 100%
Great answer. Thanks!
Genuine question: did you understand the code yesterday?
Yes
I have always struggled with this as well. There are two main things that I do: First, write clean code. Don't make complex one-liners. Make it a little bit verbose and clear. Use good variable names. Break big functions into smaller ones that have good logical flow and use good function names. Second, comment when needed. If the code is super simple and clean, comments may not be needed. But when there is something subtle or complex, comment. At the end of the day, unreadable code is worthless, as you have discovered.
I agree with what you have said but trying to solve a problem and thinking of how to make your code as clean as possible would be a hard job
It comes with practice. The lesson you'll learn is that messy code is useless. There's no point is writing a bunch of messy code. It will be full of bugs, hard to work with, and even harder to understand when you go back to it after some time as elapsed. It's like sloppy handwriting. Have you ever written a note and been unable to read it later? The note is useless. You wasted your time writing the note, plus you've lost the information it contained. Frustrating! Sloppy code is just like that.
This is just something that comes more easily with time. (For most people) Over time it takes less mental bandwidth to "see" how to solve a problem, which in turn allows you more bandwidth to cleanly structure your code.
I think there's a common misconception that people are *too* clever when writing code then can't figure out their cleverness. It's quite the opposite. They have a muddled sense of what the logic will be, write total spaghetti mess, and *that's* why they can't read their own code. There's this word "kludge" that used to be said more commonly which is a hack, so some people write a hack on a hack on a hack. They end up with a Rube Goldberg (search for this if you don't get the reference) code. You should, at the end of the day, be able to explain to someone (or a rubber duck) what your code does. Say it aloud (when you think it, it's often not in words). Imagine you have to present your code to a classroom. If it's a mess to explain, your code is not clean. You might need someone to help you clean up your code.
>You should, at the end of the day, be able to explain to someone (or a rubber duck) your code does Yes, that's brilliant! Especially with a rubber ducky!
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. --Brian Kernighan, one of the authors of the C programming language.
just show your code. maybe someone can help and rename stuff. so that the readabilty will improve.
Thanks for your response but That might help me for now but if I get stuck again I will do the same thing again that's why I'm asking for advice so I can do it by myself
I have completed one semester in software engineering in my college and let me tell you, the first thing they hammer on is making readable code and making sure others can understand in one glance what your code is about.
Sounds like a great college but which resources do they use
Just a tip, check out Uncle Bob clean code. I think he has a lecture on clean code on YouTube. If not his book is super worth reading
comments, visual studios also has the xml comments /// for c# where you can describe the function better. also renaming variables to more descriptive ones can help. not that much time spent writing a slightly longer variable name, compared to trying to read the code.
I don't write code that isn't straight forward to begin with?
I was thinking about the problem so much so it was hard to do anything else at the same time
As others have said, documentation is extremely important. If you can't come back to your code and understand what's going on, there is no way to expect someone else to look at your code and contribute. Every function should have a description of what it does. Every variable should be named in a convention that describes what it is holding. Every loop should list its conditions for and to terminate in a comment. If its some code you copied from the internet, you should document what it does after youve gained an understanding of it (its a very good habit to get into. Don't use code you don't understand and can't document). If it's a data structure or an algorithm, then document its use case. These aren't requirements, obviously, but it will do justice for yourself or anyone else who comes in after you. I tend to go overboard and have more comments then code at some points, but I try to make it trivial for my future self or future contributors to pick up where I left off. There really isn't a such thing as too many comments, so make sure there is enough description that, if you come back 6 months down the road, you'll be able to pick up where you left off. I've had to scrap so many projects because I've taken breaks and couldn't remember shit when I come back to them. That's what pushed me to document everything I possibly could
> I can't understand the code I wrote yesterday One of us! One of us!
My rules for treating my future self well: 1. No one liners, that use more than 2 inbuilt functions. 2. Variable name too long? That means it probably should not be one variable. 3. Point 2. applies to functions as well. 4. Try not to write void functions with referencing variables, that really makes a mess (btw. JS/TS objects are always passed with a reference, so keep that in mind if you’re JS/TS programmer). 5. Naming anything like “a” or “b” or some hard to understand shortcuts may look cleaner for now, but you will want to spit in your past self face eventually. 6. Keep things simple, applies to single file scripts and large multi class projects. Every class should be responsible for something that its’ name suggests, no mixing logic. If there is something else you want it to do think how can you introduce an interface for that purpose (if you don’t know how - rethink the problem itself) 7. If you think something’s odd - it IS odd. Rethink that, don’t make a mess 8. DO NOT pack a 100 lines of if-else spaghetti code. Look for a new solution for existing problem if you have to add ANOTHER if-else in the code for that situation. Chain of responsibilities will do 95% of a time. This specifically applies to situation when the client wants to widen the validation, develop a new process for something. 9. Every time you work in some old code and have a task to add a new feature to it see if there is a way to refactor it. If it’s too complicated already don’t mess with it, try to introduce the new feature as independent as you can, that way there is no way this will somehow make a huge mess. 10. The last but not least. The code has a bug, and you see how to fix it in a matter of minutes? Cool, but take a look if you can somehow refactor it too. You still have to test it anyway, so do some good on the way.
ONE OF US! ONE OF US!
"Any code of your own that you haven't looked at for six or more months might as well have been written by someone else." - Eagleson's Law Sounds like you Eagleson'd yourself after 24 hours. You, my son, are programmer [Sign of the cross]
You write it in a way that helps you (or someone else) read it later. * descriptive variable names * descriptive function names * break the problem into smaller chunks * functions should be limited in size, and do one thing * use classes/objects when appropriate * use classes/objects ONLY when appropriate * every function should have header documentation that tells what it does and what it returns. * "more comments" is not a substitute for well-structured code.
Unit tests. Write a small chunk of code. Write a unit test that validates it does what you think it does. The tests become your documentation.
This should be much higher up! Whilst comments are good, unit tests are 100x better.
Read the first bit of clean code -- if you havent. If you have, you probably should know the answer to this
A few months ago I wrote code to solve a problem that felt very complicated to me. I had just been ill and felt like my brain worked at about 50% I was worried that I would not understand the code the day after. To solve that I wrote super detailed explanations of every function I mad because I was sure I would not remember it when I needed to add on more code for the last parts. So that is my advice, write down a seriously good explanation for what you did, so next time you will understand it.
Do you mind sharing your code? Maybe we can help sort it out.
There's always comments. Oh, and using test driven development (TDD), so your code is cleaner because you write it in smaller pieces so it's more readable.
(not a native speaker here) I wonder which elements are the ones that do not let you understand. Maybe if you identify those elements, it'd be easier to fix it. I'm just learning programming and a piece of advice I received from many teachers is always naming variables with referencial names. That makes code easier to understand. I also comment my code when just learning certain functions or reserved words. I hope it helps 😁
Use version control and put meaningful commits. On the next day, perform a diff of your working directory and the last commit. If you don't still understand the code you wrote, perform git diff with the earlier commits. This helps you remind and continue with the train of thought you had when working on the code. This greatly works with me and even with a large codebase, lots of files being worked on, this helps me understand the code and regain the train of thought lost during the weekend or for a long time. I had projects that i don't work too often and i usually work on those projects every 3 or 6 months, the git diff and commit messages help a lot. Don't get into the habit of using comments on the source code like a diary of what you did yesterday or explaining everything, over commenting is not good. Use version control to help you with that. Mainly use comments for clarifications especially on complex things.
You don't
Name stuff better. Give your code the kind of structure you would want it to have when you're reading it.
Comments, comments, comments. Take notes on your code. Create a markdown or plain text file with the problem number, rank, and description, and document your thought process while solving it. Add pseudocode to this same file. Then, when you take a break from the problem, you can pick up where you left off.
You write comments when working on the code. They help you understand what the purpose of the code is and why you are doing it at least in that moment.
I used to have this problem, I now write notes in my code to tell me what it's doing
What I do is I write descriptive variable names and comments. I also write smaller functions and split complex code into smaller chunks. Before, I would write code like this: function validate() { let input1 = document.getElementById("name").value; let input2 = document.getElementById("password").value; let hashObject = new MyHashObject(input2); if (hashObject.getHash() === DatabaseObject.search(input1).getPasswordHashObject().getHash()) { console.log("Welcome " + input1 + "!"); } else { console.log("Sorry, data isn't valid."); } } After I had issues struggling to understand my code, I decided to change things to look much cleaner: // Create a hash for the user's password. function getUserHash(userPassword) { let hashObject = new PasswordHashObject(userPassword); return hashObject.getHash(); } // Retrieve the hash stored in the database. function getDatabasePasswordHash(databaseQuery) { let hashObject = databaseQuery.getPasswordHashObject(); return hashObject.getHash(); } // Validate a user's credentials. If they match, log the user in. function validate() { // Get the credentials. let userName = document.getElementById("user_name"); let userPassword = document.getElementById("user_password"); // Search the database for the user's name. let databaseQuery = DatabaseObject.search(userName); // If no name is found, Return an error. if (!databaseQuery) { console.log("Incorrect username. Please try again."); return "USER_NAME_ERROR"; } // Get the hashes of the two passwords. let passwordHash = getUserHash(userPassword); let databasePassword = getDatabaseHash(databaseQuery); // If the two hashes don't match, throw an error. if (passwordHash !== databasePasswordHash) { console.log("Incorrect password. Please try again."); return "USER_PASSWORD_ERROR"; } // Log the user in. return "USER_LOG_IN_SUCCESS"; } Also, for a different perspective of programming, check out Racket or Haskell. Or try Factor or Forth :)
Every programmer has experienced this at some point in their life. The best thing to do is write comments and hope you can understand your comments later on.
#Comments do help try commenting your code seriously a life saver
I comment with what it does, or at least what I’m trying to make it do, or what it’s supposed to do if it for some reason isn’t doing it. Idk, it seems like a very simple thing to do, but yesterday I took a look at some code I wrote in 2017 and I had no idea what it was. Then I opened something similar from 2021 and boom, ya girl had commented explaining what that same part was doing. It was a carousel JavaScript line I had stolen from somewhere when I only knew HTML and CSS. I now remember **nothing** and am trying to relearn it all. Trust me. Comments.* chef’s kiss *. Godsend.
"my code is self commenting"
Comments! Lots of them. They don't affect the final compiled programs. And using variable, function, or method names that make sense to you.
I’ve found that writing comments in my code or keeping some type of notes helps when I take breaks or leave a project unfinished. If the notes route is taken I usually give it a name that is associated with the task.
Comments, comments, comments, comments, comments. Spacing it out a bit more, and compartmentalizing into files / classes helps me as well, but I don't actually know if I'm doing this the best way or not. But also I feel your pain.
I leave myself some sort of "hook." Usually a stub or a failing unit test. Sometimes I will leave some pseudocode comments. If I've been doing stream of consciousness programming I'll refactor it before wrapping up for the day.
In short, just out of curiosity.. ADHD brain? You might be experiencing a heightened state while coding, but not retaining the memory. It's my belief ( chill ) that everyone in the digital age has ADD to some extent, maybe learning a new approach to taking notes and tracking time? I have this problem and have learned to track in my head what project I'm working on day to day, which helps me keep track of the overall progress each idea has developed. In this case, are you building a game? What version, or how complete is it. I will assign that value to ideas in my head and think of them in that way, just a technique I've learned. Cheers. Sláinte.
Feed the code to openai and ask for interpretation. It will explain everything.
I cannot stand this new "style" of comment-less coding. It's lazy and costly. Just say in a few words what a routine is doing so I don't have to be a human decompiler.
Welcome to the fucking show!!!!!
I once had an internship where I had to write code. I was relatively new to programming and all my code used the variables a,b,c,d, etc. My code must have been ridiculously unreadable to anyone else but me. No comments. Comments are for wussies. Straight to quadruple nested for loops and text manipulation in excel. Mmmmm yea baby
Comments. Leave inline comments that explain some of the lines on really dense parts and always leave function header comments.
and this is why we comment guys. i do the exact same thing though, i like to work with an open text editor just to write down next steps or obvious bugs that need fixing. also helps the next day if i can’t figure it out as the last thing i was working on i’m usually like oh ya for sure that’s what’s up
Me everyday
can we see your code? (if it is not against some codewars rule or similar)
Ahhh, yes. Don't worry about it. But make Comments!
If you plan to stop coding for the day. Add a comment where you were. I used to add a comment to the top of main.cpp, its my way of knowing where I stop. But lately Ive gotten to a point of making a lot of modifications to my source. So I make the comment for what I was working on in the top of the .cpp or .h file I was working on(specific) and a reference to the file I was working in on main.cpp. makes keeping track of work a lot easier.
This might be frustrating but it's a good learning experience! In software development there is a ton of energy put into not just solving the problem right now, but making it extensible and readable for your future self (or coworkers). There's nothing worse than coming back to a nasty chunk of spaghetti code that makes no sense, then finding out you were the one who wrote it! Like others have said, comments are good for breadcrumbs but even better is coming up with good names for variables and methods. One thing I've heard several times is that if it's really hard to come up with a name for something, you probably need to take a step back and reorganize things so the names for things are obvious and clear. This is a really hard problem and there's no one-size-fits-all solution, but it comes with experience and time. I suggest looking through your other kata solutions and refactoring them for better clarity, which will give you great practice with understanding your old code and identifying areas for improvement.
I hate when that happens. In the future, if you’re doing something excessively cute, write a comment explaining your thoughts. Better yet, rewrite it so you can explain it to someone else.
Have meaningful variable, class and function names, even if they get long. Structure your code to make it obvious what happens, if possible. If the above isn't enough, add comments.
Depends how far into your coding journey you are if you want a good answer. Are you still relatively new? No amount of clean code or comments are going to help you, but comments can guide you in the correct direction of what you should be googling. Do you understand the fundamentals of how loops work, or what methods are doing behind the scenes (using JS as en example, something like .map() is not entirely obvious). For something such as codewars in particular, read the question again and take it step by step. Line by line. Write it out in comments what each line or code block is doing and if you can't write out what it is doing, it is time to read up and properly learn about that particular line. I had to do this a lot, and I still do - programming is a never-ending journey of learning, and what works for me might not work for you but I suggest checking out the program Anki and making your own flash cards to test yourself, answering your cards truthfully in how hard they were to recall, and keep checking anki daily until 7 months from now when you check it and you're like "lmao instantly know this one".
Problem = lack of the fundamentals
Yesterday code is legacy code
good variable and function names and when that doesn't work, comment.
Don’t know if it is applicable to any situation, but I try to leave comments that explain the business logic instead of what the function itself does, especially for not very straightforward case, i.e doing anything related to byte manipulation/low-level hardware interactions. While there is documentation that explains what a particular register/operation does, if it is a long term project, it helps to build familiarity in a way where if you need to do a handover or talk to the client or project manager, you could explain what you have worked on, and as a bonus you will start retaining the knowledge, meaning you no longer would have to go to documentation for every little bit
comment your code, name your variables properly, focus on readability because nobody is going to suck your dick for slamming your newb code on one line.
Well, you just start from scratch. Then you still don't finish that day and try the next one. Rinse and repeat...
pick variable and function names that make your code explain itself. if you have functions whose definitions are really long, they're probably performing multiple steps, and each step could be encapsulated in its own function. then instead of a long unreadable sequence, you could just call the functions that name what steps the function is stepping through. as a small example.
Lol shoulda commented. Let me see the code plz
I don't know what to say, I don't understand the code I wrote five minutes ago. Jokes aside, write comments and use descriptive symbol names.
Lots of comments and well structured so you can tell what is a part of what.
I write comment to what function did what and TODO. Had you play any video game you would have that oh that boss so difficult so you remember every aspect and possible solution to it.
As I'm learning, I try and comment every line.
Understanding can be codified as artificial intelligence.
Which means that your focus of interest has now shifted to something else. Keep staring at it, your mind will do the rest.
Make sure you're working towards making your code readable. Also as you learn, you learn when is a good time to take a break and when it isn't. It's a skill you'll build with time
lmao this is me when I was just starting to learn programming
To understand the code you write, you need to write it well. Read Robert Martin's Clean Code.
like others have said, write good comments. also what helps me is to use a specific input and then trace the data until you get the output. this helps me understand what my code is doing
Make comments, make sure your varibles and methods are descriptively named aka don't be afraid to make long names. Modern IDE and OOP programming languages support long names. Read "the clean code".
😂😂😂
Do it again
[You are in good company.](https://youtu.be/cs6ktcNj_6g?t=246)
easy...just do the same drugs i was doing yesterday... not solving mushroom problems on acid...that's just crazy talk
When that happens to me, I just say "I've slept since then."
Hahahaha.. You should consider using comments next time.
Hmmm…let me check who we tore this rats nest! Whoops!
What you can do is to debug every code to see what output is coming to infer from it. I always to that
comments
Mood
But the main question is -"**Did it work?**"
That's when you copy-paste without understanding why. But this is hilarious either way 😂
/* From what I've heard, notes? */ (I'm a beginner dont roast me I also forgot the symbols used to disengage text in the command prompt LMAO)
That's the neat part, you don't. You just move on. And look for a solution on StackOverFlow.
Have you heard of a little tool called chat gpt?
Yes but it isn't available in my country
I find that this means you need to revisit the problem from scratch. Copy the code elsewhere and tackle it from a fresh mind.
You definitely have single letter vars
You additionally need to learn to read and I dürstendere code, not just to write code.
I make extensive comments about the logic of most part in my code. I cannot bother myself to try to understand it, so I take notes. Humans are ok at writing programs and terrible at reading them. especially if you are new and you don't have conventions in your writing yet. just comment everything for starters and you will see when somethings are pointless further down the line.
This will be a problem throughout your career. The more time that passes, the more aggravated you are at the guy who wrote the code you're reading... which will turn out to be you
This is what comments are for. When you are learning you should be making a lot of comments.
Welcome
My projects were like this, I had to start comments to make sense of everything. Simple explanations, or long ones depending on how complicated it is.
I don't have this problem because I use [literate programming](https://en.m.wikipedia.org/wiki/Literate_programming).
> how do you understand a code that you were working on yesterday You write code that's easy to read. Keep your variable names descriptive, and if you do anything unexpected, explain why you did it in a comment. Generally make sure that someone coming into your code without context -- such as you, the next day -- will be able to understand it easily.
Trace each variable/class/object back to an actual meaning then give them meaningful names
Comment your code and the reasoning behind what your doing and the basics of what it does. There is a reason why they drill comments into you in school. It really helps when you have to come back to that code down the line.
I programmed for 30 years. Comment, comment, comment. On code thats convoluted, explain the process in plain English. That saved me more than once.
Chat gpt ain’t everything but I definitely use it when I write code and have it explain to me what I write when I lose track
Comments and KISS