Linus's Laws of Writing Readable Code

  Рет қаралды 91,555

Kantan Coding

Kantan Coding

Күн бұрын

Пікірлер: 234
@sven-o
@sven-o 3 ай бұрын
If you care about tab width you got no real issues
@DemPilafian
@DemPilafian 3 ай бұрын
100% correct. That's why all real developers work alone and never share files with anyone.
@sven-o
@sven-o 3 ай бұрын
@@DemPilafian Real devs can just adjust tab width if it really matters to them
@jonnyso1
@jonnyso1 3 ай бұрын
I agree, the lead maintainer on the Linux Kernel has no real issues to worry about.
@dasmonstrum27
@dasmonstrum27 3 ай бұрын
No cowboys allowed on my squad, since I've made the pipeline. Use Linter or expect an error message blocking merge request.
@DemPilafian
@DemPilafian 3 ай бұрын
@@sven-o In the real world, tabs result in endless problems. There's a reason well-intentioned projects start off with tabs and switch to spaces but never the other way around.
@nerdycatgamer
@nerdycatgamer 3 ай бұрын
1:35 You've got the example wrong. We're not `grep`ing the output of the program for the error message (splitting up the error message in the source code isn't going to cause it to be printed any differently anyways): we're `grep`ing the source code for where that error message is, so we can see under what circumstances it gets printed.
@kantancoding
@kantancoding 3 ай бұрын
My understanding is that it’s both. Splitting the error message in the source code will cause the message that is printed to be on multiple lines therefore making filtering logs a bit annoying which is what I was showing in the example. The same thing applies in the reverse case when grepping the source code for where the error message is. The reason I didn’t put time into explaining that is because most modern logging implementations will have the file and line number etc where the error was thrown in the stack trace so you usually don’t need to grep the source code like you mentioned.
@VenusCyberTruck
@VenusCyberTruck 3 ай бұрын
✅💯
@vandelayindustries2971
@vandelayindustries2971 2 ай бұрын
@@kantancoding But unlike what you claim in the video, changing it to string concatenations doesn't solve the issue then? Grepping the entire message will not get you the culprit line, because you don't know where to put the "+" in your search string
@kantancoding
@kantancoding 2 ай бұрын
@@vandelayindustries2971 yes, the solution I provided is for grepping the logs which is imo more important for the reasons I’ve already mentioned above. If you want to grep the actual source you will need to keep the log message on one line.
@Verrisin
@Verrisin 2 ай бұрын
Both is wrong. Use clear uniq tags for each place. - Using the "readable" error message text is horrible for either purpose.
@tomershechner
@tomershechner 3 ай бұрын
Smooth transitions between concepts, meaningful commentary and instructive examples. What a nice video!
@cajonesalt0191
@cajonesalt0191 3 ай бұрын
I've never really understood the "don't use comments to explain how something works only why it's in the code" argument, but if the example in this video of explaining "how" is what that rule is supposed to stop, then I totally get it now.
@kantancoding
@kantancoding 3 ай бұрын
It’s like, if you are spending a lot of time explaining how your code is working… usually (not always but usually) that code is 💩 So spend the time making the code better instead of explaining how bad code works.
@pdgiddie
@pdgiddie 2 ай бұрын
Writing good code is not just about writing code that works. It needs to lead future maintainers through its intention. That's why naming things well is so important too.
@nemanjatrivic9505
@nemanjatrivic9505 2 ай бұрын
If you are implementing some known algorythm then just put a comment and link the source, you will do everyone a huge service.
@steve-wright-uk
@steve-wright-uk 2 ай бұрын
Comments are best for WHY not HOW
@nemanjatrivic9505
@nemanjatrivic9505 2 ай бұрын
@@steve-wright-uk if you implemented algorythm and didn't invent it yourself, why wouldn't you link the source to help people understand what you did?
@chonkusdonkus
@chonkusdonkus Ай бұрын
tabs are configurable in your editor and objectively better
@spfy
@spfy 3 ай бұрын
I was confused by what you said about being able to split up lines by concatenating them. In your example, sure, the program output is still in one line so it's possible to use grep. But what if instead, you wanted to find where that error message was in the actual code? Now you can't find it, because it's split up...
@christopherjaya342
@christopherjaya342 3 ай бұрын
It's a good practice to seperate the log messages strings from the main function by using char * variables.
@spideybra
@spideybra 2 ай бұрын
I'd argue that searching for the message in the source is way more common than grepping a program output. You would usually see the log when inspecting the output after an error, then search for it to find out what went wrong in the code.
@pwhqngl0evzeg7z37
@pwhqngl0evzeg7z37 2 ай бұрын
My hope is that in some languages a preprocessor will assemble such split string literals so that one can grep that output instead. I believe this is true for C(++), for example, and I suspect some nonstandard preprocessors are available for others.
@IgorGuerrero
@IgorGuerrero Ай бұрын
Two of my favorite rules from Linus is "early returns" and "prefer positive conditions over negative"
@magnusmarkling
@magnusmarkling 3 ай бұрын
How does Linus come into all this? Didn't hear him mentioned even once in the video.
@lightningspirith
@lightningspirith 3 ай бұрын
Never heard him talking about these rules either
@kantancoding
@kantancoding 3 ай бұрын
These are literally all from the linux kernel coding style guidelines which he wrote. www.kernel.org/doc/html/v4.10/process/coding-style.html
@chrissherlock1748
@chrissherlock1748 2 ай бұрын
@@kantancodingouch
@maleldil1
@maleldil1 2 ай бұрын
@@kantancoding you might want to make it clearer, and perhaps link the style document in the description.
@mikebond6328
@mikebond6328 2 ай бұрын
@@maleldil1document.? What’s that?
@ktostam3478
@ktostam3478 2 ай бұрын
Strangely meditative, straight to the point and so smooth that it doesn't need outline/introductions to connect the topics. Well done!
@AlexanderVulpes
@AlexanderVulpes 2 ай бұрын
I 100% agree about comments, they're supposed to explain the "what" more than the "how". It's a good way to help future devs find bugs too.
@MrHaggyy
@MrHaggyy 2 ай бұрын
With comments, it depends on what the code is for. When learning a language, they are a great place to dump ideas. Explain to you what you are trying to do and give each implementation some text what it's actually doing. Helps to understand what the heck you did 3 weeks ago, benchmarking, writing assignments, etc ... When writing code that people work with drop the explanation. If you can't read the code you have a skill gap or communication issue in your team. But keep your problem description and the scope of your implementations. For example copy data/error_msg/log to buffer in the string example. When reviewing you can count the occasions where "text" needs to be copied into a buffer and reason about how many "copy to buffer" functions you need. Maybe one is a fast copy of 16 chars for an ID number, while the other copies a name like your version in the video. Then there would be code for teaching. In that case, explaining the code is the primary job of comments. But it would be great if more sources were already adding a mature way of commenting and how to work with comments, so people get used to it from the start.
@fritzschnitzmueller3768
@fritzschnitzmueller3768 2 ай бұрын
Worst take ever - Bro have you ever worked on a codebase with 40 different other people? If so, and you still say "Dont document bc your code is self explanatory", then you're enjoying pain because let me tell you, the code of the 39 other ppl is most likely not self explanatory in a lot of places. COmments dont hurt. Just be mindful and if you code review, make sure comments are updated. Like yall read to much Uncle Bob and clean code BS
@MrHaggyy
@MrHaggyy 2 ай бұрын
@@fritzschnitzmueller3768 You sound fun to work with. Disagreeing with a strong opinion, to claim the same statement. While learning a language, commenting on what while(char_ptr++){} does might be a good idea. If while(char_ptr++) confuses the heck out of you, you might not be the person to review a large codebase jet. If you teach coding explaining what while(char_ptr) does is your job. Also if comments are your only source of documentation I'm really glad I never had anything to do with your Uncle Bobby.
@fritzschnitzmueller3768
@fritzschnitzmueller3768 2 ай бұрын
@@MrHaggyy It has nothing to do with being fun to work with. Its just that these arguments are just non realistic. EVERYONE I work with would agree, there wouldnt even be an discussion about something so silly. Like do your clean code and stop explaining things. Ive went through it. I have a istory of pushing out a lot of projects in the medTec field, by building upon what others have build. Ive implmented features in others codebases. IT doesnt seem like a lot are doing it, because no one that does the same and knows what hes doing, would claim so. Im just tired of so many opinions without anything to back it up. Its amateurish..It sounds like Im discussing with a bunch of universits students
@Rekwalde_PoE
@Rekwalde_PoE Ай бұрын
I generally think about it like "Will I ever print this code via my printer?", the answer usually gives me clarity on what my print width should be. Because I don't have a printer.
@steinarst9084
@steinarst9084 2 ай бұрын
3:45 - "So that how it works, is obvious." - does cool animation with code, proceeds to put ad over code - you villain xD Great video. Loved the bit about indentation.
@kipchickensout
@kipchickensout 2 ай бұрын
"Don't trust people who don't put swear words in their code comments" - Fireship, slightly altered
@PJutch
@PJutch 3 ай бұрын
I disagree with 8 tabs example. I used to reading code 2 times more zoomed in than an example you've showed. This makes "too far to the right" mark go to, like, 4 levels of indentation. And also you've showed an example in Go which isn't an OOP-obsessed language. In C++ you'll get 3 levels of indentation just from method in a class in a namespace, and having 24 space nothing always at the start of the line seems bad for me.
@fuzzy-02
@fuzzy-02 2 ай бұрын
Indeed. The best advice I learned in coding is that all these programming tips, even languages themselves, are simply philosophies of some person, so don't make them sacred texts. My laptop screen isn't thay wide so I also prefer 4 char identations even in a language like Go
@fritzschnitzmueller3768
@fritzschnitzmueller3768 2 ай бұрын
8 spaces for a tab is criminal - The whole vide is a bit of a stinker as c++ dev ngl
@Navhkrin
@Navhkrin 2 ай бұрын
@@fritzschnitzmueller3768 Yeah, it makes no sense, 4 spaces is sweetspot and that is why it is default on most IDEs
@RavenMobile
@RavenMobile 2 ай бұрын
I use 3 spaces for tabs, and keep the code not wider than 80 characters except in special circumstances. If code will be much longer than 1-2 pages, I start refactoring and adding well-named functions.
@ReneSaarsoo
@ReneSaarsoo 2 күн бұрын
I'm pretty sure the 8-space tab convention comes from terminals treating tab characters as 8-chars wide. When you use terminal a lot to browse code, then it's helpful when the indentation remains the same as in your editor. (And it's not only terminals. Browsers show tabs as 8-spaces wide in textareas, and lots of other software.) There is of course another fix for this problem - use spaces. But if this for some reason doesn't fly, 8-space tabs is the only option left to solve that problem.
@unexpectedkAs
@unexpectedkAs 2 ай бұрын
Excellent examples! Usually guidelines are difficult to convey because most examples are too trivia, simple and or unrealistic/ academic.
@mrpocock
@mrpocock 2 ай бұрын
Tabs depend on the language. For example, it's virtually impossible to code java with 8 space tabs as it is all nested scopes, inner classes and so on. Languages like rust with his pattern matching let you have far fewer nested or changed if statements.
@normanross3422
@normanross3422 Ай бұрын
I've always found comments that tell you "why" rather "how" are much more useful. Mostly I can see "how" the code is working - there's plenty of times though I've wondered WTF!? were they thinking when they did it this way? (There may have been a good reason - or there may not...).
@fg786
@fg786 3 ай бұрын
I usually write comments on the how and why when I come back to the code later and can't figure it out in a couple of minutes why I did it this way. I mean it's no big deal, there are additional lines that don't bother performance or disk space at all. An issue arises when it's more comments than lines of actual code, or something along those lines, when the code reading flow is interrupted by comments.
@maxsamarin9002
@maxsamarin9002 3 ай бұрын
Agreed, I would rephrase the comment tip as "Don't write a long explanation comment if you can rewrite the code to explain itself, and be SHORTER than the long comment". Also assuming that rewriting the code to be longer doesn't increase performance cost. Sometimes smart one-liners aren't there just for the sake of being shorter, but to actually do something in a more performant way.
@MortyCJ
@MortyCJ 2 ай бұрын
Imo comments aren’t for you. If you need comments to understand your own code there’s other problems happening.
@siya.abc123
@siya.abc123 3 ай бұрын
2 character indentations are for tiny todo apps. Any large code bases must use 4 characters for legibility
@bozdowleder2303
@bozdowleder2303 3 ай бұрын
You only need 4 spaces if you have multiple indentation levels. Otherwise 2 will suffice. It's not about the size of the code as about how many indentation levels exist in the code
@pwhqngl0evzeg7z37
@pwhqngl0evzeg7z37 2 ай бұрын
​@@bozdowleder2303The way I see it is even if 2 is good for some people, 4 will only make it more legible. Unless you need to refactor your code. But tabs are better anyway.
@fritzschnitzmueller3768
@fritzschnitzmueller3768 2 ай бұрын
@@bozdowleder2303 Bro if you have multiple devs working on a codebase you stick with 4 EVERYWHERE. Stop obsessing over indentation. You dont use tabs because you'll end up with different indentations in your whole codebase, since ppl programming on different Operating Systems will use different tabs
@ewhac
@ewhac 2 ай бұрын
Your next exercise: Illustrate that your "refactored" string copy routine compiles to the same or better assembly language than the original. Show this is true on all platforms (x86, ARM, RISC-V, 68K, etc.).
@jm-pi1kd
@jm-pi1kd 3 ай бұрын
aw man, i use different indentations for different languages. i follow the standards. for python, i use 4. for bash, i use 2. for c, i use 8. but it does not really matter. just go to vimrc and change tabstop and shiftwidth and remove expandtab. your identation will automatically update. you might have to :retab if you were using expandtab before. if someone else gives you a project, change your tabstop and shiftwidth to match the indentation of that person's project. if they're using spaces, set expandtab. match your vimrc settings with that project's settings so that everything is uniform and consistent and easy. if youre working on multiple projects with different indentation levels.... then..... if theyre different languages, autocmd will be fine. if theyre the same language, then..... if you know vim, you'll figure it out.
@kantancoding
@kantancoding 3 ай бұрын
Good points :)
@luizAugustoll
@luizAugustoll 3 ай бұрын
I didn't know the defualt is 8 in c.
@jm-pi1kd
@jm-pi1kd 3 ай бұрын
@@luizAugustoll maybe it was 20 years ago. I looked it up today and most people prefer 4 in C today. i don't remember which standard i read, whether it was GNU C Standards or the C used in Linux development but one of the two said to use 8 spaces per tab. the default in vim is definitely 8 though. you'll have to add tabstop and shiftwidth to change it from the default to 4 spaces or 2 spaces.
@AliceTurner-q3f
@AliceTurner-q3f 3 күн бұрын
I agree but i think indentation resolves when you should be resolving a value before you use it. For instance in Rust it can use heavy indentation, if you don't know what you are doing with it. But sometimes you just need to resolve the value then operate on it. It's not specific to Rust it's something all programmers should know, which i think most of use learn from just programming
@I_am_Raziel
@I_am_Raziel 3 ай бұрын
Tabs with 4 chars configured
@liamappleyard6495
@liamappleyard6495 3 ай бұрын
Only true answer
@ifp5
@ifp5 3 ай бұрын
It is much easier to prohibit TABs in your VCS than configure every single editor and utility, given that some of them are 3-rd party and/or not configurable.
@MrHerbalite
@MrHerbalite 2 ай бұрын
@@ifp5 Dump tools that force you to a certain style. I sure did, and it helped me in many ways. Working on space only projects. Change it to a tabbed one for work, and when committing it, it is being feed back into main using spaces. Everyone is happy. Goes for any other combination of problems. Space|Tab discussions are so last century issues to me.
@ewhac
@ewhac 2 ай бұрын
Then your editor is mis-configured, and you _will_ have problems when loading other people's code. *_Hard TABs are modulo-8. Period. No exceptions._*
@I_am_Raziel
@I_am_Raziel 2 ай бұрын
Tabs are the best, because everyone can configure his IDE to display whatever they need: 1, 2, 4, 8 or something else. You guys can do whatever you like, but for me, THIS is the best when it comes to indentation.
@uumlau
@uumlau 2 ай бұрын
If a doofus is going to have 20 levels of indentation, I seriously want only a 2-character indent. I'm the one who has to read the 20 levels of indentation, not the guy who wrote the code. Then I can rewrite it in a sane way.
@MrAbrazildo
@MrAbrazildo Ай бұрын
2:40, these cases should be put in array: 15% faster and the code doesn't grows downside too much. C++ example: const auto Animals = { "dog", "cat", /**/ "last1" }; // All cases. const auto ChosenAnimalPtr = strstr (Animals.data(), tolower (animalType)); // Returns Pointer of the match, not case sensitive. // TODO: check for nonmatch (default case). const auto ChosenAnimalIndex = std::distance (Animals.data(), ChosenAnimalPtr); // That distance from the beginning is the index. ++animalCounts[ChosenAnimalIndex]; 3:53, the previous comments were given a C lesson. I still argue for concise code. So: while (*dest++ = *src++); // Copies string src to dest.
@wjrasmussen666
@wjrasmussen666 3 ай бұрын
Where is Linus other than in the thumbnail?
@kantancoding
@kantancoding 3 ай бұрын
He's literally everywhere since every single one of these are from the linux kernel coding style guidelines which he wrote. www.kernel.org/doc/html/v4.10/process/coding-style.html
@isaiahpan
@isaiahpan 2 ай бұрын
Hm. I have to disagree with your last point. It is far more useful to describe the "why" rather than the "what". The "what" should be readily obvious if you wrote the code correctly.
@Sapo-san
@Sapo-san 2 ай бұрын
as stated in the video and what I agree with: comments should point out "what the code is supposed to be doing", not "how is it doing it". if anyone is questioning "why", then something it's being hardcoded for a VERY specific situation which in my experience is not a great practice yet sometimes it is unavoidable
@isaiahpan
@isaiahpan 2 ай бұрын
@@Sapo-san I think if you need the "what the code is supposed to be doing" then you've made it too complicated. A function named addTwoNumbers is basically all the "what" that you need already. The "why" isn't always needed, but that is info that you cannot get from the code itself. There are often decisions made in the external world that cause a code to be written in one way or another, a common being "this is a temporary addition to allow my boss to display cool metrics to investors" which turns out no so temporary...
@kipchickensout
@kipchickensout 2 ай бұрын
@@Sapo-san It happens more often than one thinks, at least what I saw. For example wWhen you want to parse some IDs and have to do bit manipulations that might look senseless to reviewers if not annotated, or mention why you'd want to use a database transaction in a specific scenario
@giornikitop5373
@giornikitop5373 2 ай бұрын
are we sure that "while (*src++ = *desc++)" will not overflow?
@zytr0x108
@zytr0x108 2 ай бұрын
It should be while (*dest++ = *src++); but no, just from that line you can’t be sure. A good dev will of course (try to) ensure that the string pointed to by src will NUL-terminate and do so before dest reaches the end of the buffer, but you would need to see the rest of the program to be sure it won’t overflow.
@giornikitop5373
@giornikitop5373 2 ай бұрын
@@zytr0x108 oh, yeah, dest=src is the correct. haven't programmed for a long time but it seems to me that this will error out in either case. does it make a difference if it's plain C or C++? will it keep increasing the index of src/dest, until one is out of bounds? where is the condition? meh, can't figure it out. have to start from scratch...
@zytr0x108
@zytr0x108 2 ай бұрын
@@giornikitop5373 The whole expression *dest++ = *src++ evaluates to the value of the assignment (*src). Since in C the value 0 is interpreted as „false“ and every non-zero value as „true“, the while-loop will continue copying until the expression evaluates to 0. This is the case when the byte at the memory address of src is set to 0. Since strings are NUL-terminated (at least they should be) the loop will continue until the end of the source string is reached. There are a couple of ways how a memory problem can happen: 1. Either pointer is a NULL-pointer that will get dereferenced. 2. Either pointer points to unallocated memory and it will read from/write to potentially critical memory. 3. src isn’t NUL-terminated. In that case the program will just read memory possibly past the buffer (and maybe read vulnerable data). 4. src is longer than desc and therefore the loop doesn’t terminate after the end of the dest buffer is reached. The program writes into possibly unallocated memory and maybe even writes to critical variables. So more critical than the loop itself is what happens outside of it because that’s where we need to ensure that the pointers that get used are suitable for the operation.
@Milan_Openfeint
@Milan_Openfeint Ай бұрын
@@giornikitop5373 The "result" of operator= is the value being assigned, so the while() tests the character that was just copied. I.e. it will stop after copying the terminating \0 character.
@giornikitop5373
@giornikitop5373 Ай бұрын
@@Milan_Openfeint yeah, i get it now, thanks. the value readed from src (and writen to dst) is the value while checks, i was a bit confused by the pointers and forgot how value assignment works in c.
@MisterDan
@MisterDan 3 ай бұрын
Nicely presented!
@kantancoding
@kantancoding 3 ай бұрын
Thanks! And thanks for watching :)
@MisterDan
@MisterDan 3 ай бұрын
@@kantancoding My pleasure, I write tutorials so I appreciate your work.
@tirthasg
@tirthasg 3 ай бұрын
Off-topic question: What VS Code theme and font are you using? Looks good.
@marcosduvannitolarodriguez1933
@marcosduvannitolarodriguez1933 2 ай бұрын
It looks like it's Gruvbox
@martonvalentin7386
@martonvalentin7386 2 ай бұрын
I am also interested in the font
@mkalk1625
@mkalk1625 15 күн бұрын
@@martonvalentin7386 I think it is Agave font
@kipchickensout
@kipchickensout 2 ай бұрын
Correct me if I'm wrong, a tab is normally 1 character (9h), not 8 Almost every code editors I've used so far replaces tabs by 4 spaces by default, so even then they're still not tabs, and most people I have seen coding are at least slightly, if not much more zoomed in than you showed and also have let's say a directory structure open on the left, and e.g. a database table list on the right and a git blame annotation to find out who they have to fire for the awful code (it was themselves two months ago). IMO using tabs is bad because in most editors it looks fine but then when you look at it in a browser, boom - your code is suddenly unreadable because it's rendered as 8 spaces I personally find it visually better to have 2 spaces in specific things like YAML and JSON
@resresres1
@resresres1 2 ай бұрын
What about comments of "i don't know why this piece of code works. DO NOT REMOVE!".
@Milan_Openfeint
@Milan_Openfeint Ай бұрын
I got used to comments being messages to my future self who will be reading the code. It could be anything from "similar code is over there" to high-level description of what it does. Now I work in a bigger company where code has to go through reviews, so many comments get auto-censored. It often pains me knowing what trouble will people have reading the code 10 years from now, but can't help it.
@yusufotar2355
@yusufotar2355 2 ай бұрын
whats the name of the font
@tarmagoyf95
@tarmagoyf95 2 ай бұрын
I don't like to have a big switch statements I usually prefer to have map and throw on null
@1schwererziehbar1
@1schwererziehbar1 2 ай бұрын
god created eight character indentation to protect us from excessive nesting.
@zbynekdolejsek8930
@zbynekdolejsek8930 3 ай бұрын
while (*src++ = *desc++); nice buffer overflow ;-) Why not use some secure version strncpy(src, desc, lengthOfDesc);?
@adrianbool4568
@adrianbool4568 2 ай бұрын
100% agree with your sentiment; although you have your src and "desc" the wrong way round in your call to strncpy()!
@pwhqngl0evzeg7z37
@pwhqngl0evzeg7z37 2 ай бұрын
snprintf is even better because strncpy doesn't null-terminate in certain cases.
@adrianbool4568
@adrianbool4568 2 ай бұрын
@@pwhqngl0evzeg7z37 Oh, you are indeed right! I forgot about strncpy's brain dead operation. I note that in MacOS, it warns not to use strncpy instead directing you to use strlcpy instead. strlcpy does the sensible thing of keeping within the given bounds whilst ensuring the NUL is present. However, if I look on local Linux box, that doesn't seem to have strlcpy. :-/ I guess snprintf it is! I tend to use Rust now, so don't need to worry about these particular issues!
@omegand.
@omegand. 3 ай бұрын
2:35 yandere dev moment
@Tiritto_
@Tiritto_ 3 ай бұрын
Undertale too
@Kerojey
@Kerojey 3 ай бұрын
That's how real programmers code, sorry to break it to you, script kiddie
@Fetrovsky
@Fetrovsky 2 ай бұрын
5 character tabs.
@lightningspirith
@lightningspirith 3 ай бұрын
I actually prefer to measure code indentation in pixels because ...
@mike_nba
@mike_nba 7 күн бұрын
I solved the first issue by getting an ultra wide screen.
@Martin-lc1sk
@Martin-lc1sk 3 ай бұрын
Code should be consistently fornatted Code should be commented Code should be concise.
@kantancoding
@kantancoding 3 ай бұрын
Consistency, definitely.. the others deserve more explanation :)
@HoD999x
@HoD999x 2 ай бұрын
Code should work
@sub-harmonik
@sub-harmonik 2 ай бұрын
I disagree with using these examples because there are better ways to do them imo. (for instance the switch you can make the 1st character uppercase. Or have an index map, or only have the case statement find the index)
@orbik_fin
@orbik_fin 2 ай бұрын
For best readability we should stop using monospace fonts, so the indentation size could be expressed in pixels, or "em" units. And why does it have to be uniform, or even constant? Editors could very well optimize display for current position so that when you have deeply nested blocks visible, the indent becomes smaller. The religious reverence that people like Linus has for tech traditions can be quite limiting.
@the_original_dude
@the_original_dude 2 ай бұрын
nothing stops an editor from "expressing" indentation in anything, so this has nothing to do with fonts. Code aligned with tabs can easily be displayed with the indentation (tabs) interpreted any way you want
@thmUNIX
@thmUNIX 2 ай бұрын
2:49 I would just use a dictionary in this case. Match one string to another and increment the required value.
@kantancoding
@kantancoding 2 ай бұрын
Yeah, but I mean, it was intentionally made like that to illustrate an example of a long function that’s not complex. But thanks for the code review 😂
@jamesaffleck4192
@jamesaffleck4192 2 ай бұрын
What does this video have to do with Linus Torvalds? The title and thumbnail indicate it would be about HIS rules, but unless i missed something, he's entirely absent and these are your rules.
@kantancoding
@kantancoding 2 ай бұрын
- “unless i missed something” You definitely missed something.
@aethernal1379
@aethernal1379 2 ай бұрын
Regarding the long lines issue, what if the problem is caused simply by long variable and/or class NAMES and you can't even sensibly shorten them, because then they'd no longer be clear and precise and so, upon reading the code, you no longer knew what is what? So e.g. you have a variable (or a class name) like $aVerySpecificPluginFromAVerySpecificModule that has to be called that, because otherwise it couldn't be differentiated from $anotherVerySpecificPluginFromAnotherVerySpecificModule, and then, in whatever line you need to use this, even if only for something very simple, like a function call without arguments or an assignment or creating a new instance of a class with such a name or whatever, you'll still have a very long line. I have yet to see a good solution to this.
@ivanmaglica264
@ivanmaglica264 2 ай бұрын
With HTML, the answer is 2 characters per tab. Nesting is inevitable there 😀
@Veloxzr
@Veloxzr 2 ай бұрын
What did you use for the nice code animations?
@VenusCyberTruck
@VenusCyberTruck 3 ай бұрын
I love ur videos 🥰🥰🥰
@VenusCyberTruck
@VenusCyberTruck 3 ай бұрын
I watch all commercials too😁❣️
@JosephDalrymple
@JosephDalrymple 2 ай бұрын
I know no one wants to restart the whole "tabs vs spaces" argument again, but I still prefer tabs above all else. With tabs, if you like 2-spaces, you can set your tab width to 2. 4 spaces? Set it to 4. 8? Set it to 8. Why force people to have _your_ preferred indentation length? Just use tabs.
@the_original_dude
@the_original_dude 2 ай бұрын
looking right now at openbsd sources. They're using tabs, but for wrapped statements they use a half-tab(4 spaces) indentation. It's very messy, they assume tabs are 8 spaces, so there are mistakes and inconsistencies regarding how spaces are used. And that's a project that's supposed to have clean code. Maybe I don't understand something, but that's an insane code style. Totally agree that if you want to have many people working on the same code you should indent only with tabs, and no spaces after tabs for alignment, spaces for alignment can only be in between visible characters.
@JosephDalrymple
@JosephDalrymple 2 ай бұрын
@@the_original_dude Totally agree 100%. We enforce exactly that at my current company. For multi-line code, either split everything on the line out to new lines with indentation, or keep it all on one-line. There are tons of clean alternatives to the whole "but you need spaces for x, y, or z!" arguments.
@noname-ll2vk
@noname-ll2vk Күн бұрын
​​@@the_original_dudeI've debated the wrapped statement indentation thing for years. My conclusion there is no perfect solution and due to oddity of using spaces there, as you describe the issue, I finally wrap using no extra indentation. While that is also not ideal it's less annoying than other methods I've tried over years. I tend to consider whatever openbsd does as fine for the simple reason they achieve with something like 50 devs more than huge corporations can, and often much better. So in some ways I tend to assume Theo is probably right because their coding practices lead to astonishing results. And they aren't geared towards mediocre programmers. It's clear that projects that will have mediocre devs working on the code have to create standards to protect against those risks. But that is probably at the price of making the code worse.
@the_original_dude
@the_original_dude Күн бұрын
​@@noname-ll2vk never saw a problem wrapping with full indentation, instead of that weird half-indentation. As I said, they have trouble following their own code style. They're efficient because they're small, not because of some dumb code style guideline. I haven't seen a single sane guideline that doesn't try to encompass too much. Also, existing code itself should serve as a guideline; writing a few things down to have an official document is pretty much meaningless.
@iamsaidumar
@iamsaidumar 2 ай бұрын
whats that theme? and what editor?
@dantenotavailable
@dantenotavailable 3 ай бұрын
I don't think you go far enough with your point about comments. Don't tell me how, don't even tell me what. If I can't get a pretty good idea what some code is trying to achieve by reading it then it's probably no better than the code where the programmer felt the need to say how it works. The point where you need a comment is when you need to explain *why* it is the way it is. For example: "This string copy ends up being used in the render loop so if you don't squeeze literally every cycle the framerate is going to tank". Ok great, now I know that if I apply the code clean up then I need to ensure it optimises to the same code and also where I should probably go check performance before releasing it to production. The key part is that if the code looks out of place then the comment is there to try to convince me that doing it this way, as opposed to the way the rest of the codebase works, was the right thing. (Oh also, interface contracts should be documented as a matter of expectation management but that's not really a "comment" even if they use the same mechanism) Also, the right number of spaces that an indent should be is whatever my auto-formatter is configured for and the correct way to get those number of spaces is to use the tab key. Also, if I want to go back to the previous level of indentation, I should be able to press backspace once while at the (indented) start of the line or sometimes shift-tab. To put this another way, the editor should act in every way shape and form as if Tab characters were being used but should only ever write the indent as space characters to the file system. I personally think that 2 characters is too little and 8 characters is probably too much but that's because i'm getting on in years and my eyes don't see as well as they used to but, ultimately, whatever is agreed upon as the auto-formatter settings is the correct value.
@DemPilafian
@DemPilafian 3 ай бұрын
2 spaces requires additional cognitive load to distinguish the nesting level. 4 spaces is a waste. 3 spaces is the *ONLY* correct answer.
@christernilsson1
@christernilsson1 3 ай бұрын
The tab size should be individual. This can be accomplished by using tabs only, never spaces. End of discussion.
@DemPilafian
@DemPilafian 3 ай бұрын
@@christernilsson1 The discussion is over only in fantasies. In the real world, tabs result in endless problems. There's a reason well-intentioned projects start off with tabs and switch to spaces but never the other way around.
@christernilsson1
@christernilsson1 3 ай бұрын
@@DemPilafian please list the reasons. Here are mine: tabs are easier to insert and delete. Tabs takes less space. Tab width can be individualized. A company can change the standard from four to three spaces with a keystroke. And the main reason: there is nothing left to discuss.
@DemPilafian
@DemPilafian 3 ай бұрын
@@christernilsson1 Tabs are theoretically better than spaces in every way. In practice, however, tabs are a mess. 1) Web pages and command line tools display tabs with ridiculous amounts of space. 2) Indentation and alignment are different, and alignment requires spaces which get destroyed by tabs. 3) For whatever weird reason, experienced smart developers occasionally submit pull requests with some indentation as spaces instead of tabs (the reverse does not happen). The real world doesn’t care that tabs are theoretically superior. Engineering managers get tired of tabs interfering with code diffs.
@christernilsson1
@christernilsson1 3 ай бұрын
@@DemPilafian Copying indented code from different ai:s and other sources will suffer from having different amount of spaces. All tools should be configurable, like VS Code.
@zx-sy1qh
@zx-sy1qh 2 ай бұрын
I use spaces no tabs ! Don't come for me Richard !
@ruixue6955
@ruixue6955 3 ай бұрын
2:31 case of long function but acceptable 2:54 never try to explain how your code works in a comment
@laurii0512
@laurii0512 2 ай бұрын
I don't care. I always make sure my code is not an overindented nightmare, and 8 char indentation will still allways feel excessive to me. 4 is perfect for me, I find it readable without being too much.
@ELStalky
@ELStalky Ай бұрын
You should not use comments to explain what your code does either, it's redundant and often goes out of sync the moment someone changes the code, then you have a lying comment which is much worse than no comment at all. Comments should explain *why* something is done because that is something the code does not contain. Code comments are not to be confused with code documentation, the latter usually is for an external interface/API and it should explain what the given function does so the internals can be treated as a black box and the function can be used without knowing the implementation details.
@yashprogamer647
@yashprogamer647 3 ай бұрын
0.24 it's the one with 4 spaces
@TheFrewah
@TheFrewah 3 ай бұрын
If you use a beautifier, there won’t be any problems. Just make sure same settings are used and run it before before you commit and make sure it compiles.
@kantancoding
@kantancoding 3 ай бұрын
If only it were that simple 🫠
@TheFrewah
@TheFrewah 3 ай бұрын
@ well, it solves many problems. If you don’t like tabs or something, just let it beautify the code to what you like and then beautify back when you check in. That’s what I liked about vb6. Having said that, there were those that wrote horrible code. My c++ code called vb6 code which was very good for what we wanted.
@TheFrewah
@TheFrewah 3 ай бұрын
@ I should mention some things I really don’t like which are not solved. I really dislike code that is written such that it’s difficult to debug. Don’t use one line to write code that does two things and no nested functions!!. A colleague of mine had a switch statement where only a few cases were considered and there was no default which he claimed would never happen. I did introduce a default and it didn’t take long before it did much to his surprise.
@anonmousse
@anonmousse 3 ай бұрын
someone else who uses agave nf, nice
@firstname4337
@firstname4337 2 ай бұрын
I like my indentations to be negative one spaces
@Ryan-gf1sz
@Ryan-gf1sz 2 ай бұрын
uh, I'm not sure, do you guys think linux code is readable?
@User948Z7Z-w7n
@User948Z7Z-w7n Ай бұрын
Yeah 2 space indentation is the company guideline at major FAANGs except for of course Python. What you gonna do about it
@UTJK.
@UTJK. 2 ай бұрын
Ok, but where’s Linus?
@MarceloBeckmann
@MarceloBeckmann 2 ай бұрын
He is talking about Linux kernel coding style
@EgemenYalın
@EgemenYalın 2 ай бұрын
3....
@kantancoding
@kantancoding 2 ай бұрын
💀
@Nahsh5ba
@Nahsh5ba 3 ай бұрын
Come on, just set max nesting level in your linter config and it will enforce the rule no matter what tab size is. Really, all of the problems have already been solved by prettiers/formatters and linters.
@Hofer2304
@Hofer2304 2 ай бұрын
The compiler should only get successfully linted code. The programmer must not avoid the linter.
@Ciprian-Amarandei
@Ciprian-Amarandei 10 күн бұрын
Number of spaces for indentation is meaningless . Numbering or marking indentation levels has more meaning. Enable "indent guides" or similar in your IDE
@ZettaiKatsu2013
@ZettaiKatsu2013 2 ай бұрын
Kantan DaYo !
@pwhqngl0evzeg7z37
@pwhqngl0evzeg7z37 2 ай бұрын
I wish more people used tab characters for indentation (with spaces for alignment.) That way the code reader can choose her indentation size by adjusting tab character display width.
@doBobro
@doBobro 2 ай бұрын
I don't think it's a good example of copy-pasted switch case with calculatable keys in a video about readable code.
@Verrisin
@Verrisin 2 ай бұрын
I disagree with all of those. (senior dev for ctx) - Ok, not fully, I get the point ... but this is not a practical way of dealing with the issues. - Yes, don't write needlessly smart/complex code, focus on reading, etc. (but explain how it works in a comment if it is an actual non-trivial algorithm. The string copy example is immediately obvious. Explain WHY you wrote something that way, assumptions, why and how you think it works, why it exists at all ... all those are fine, all EXCEPT just saying "this copies string" when THAT is obvious from the code. ) - I somewhat agree with the logging not having newlines. (but designing it so that you grep for user readable messages is awful ... next year someone will come, add localization, and something down the pipeline will break; as one example. Give each place a proper "place tag" - and of course, those do not have newlines; or even spaces, usually. Or diacritics.. - Not to mention, most (non trivial) important log messages are computed, perhaps with own functions that compose them. There is no place in code with 1:1 message found in log. )
@FatherGapon-gw6yo
@FatherGapon-gw6yo 2 ай бұрын
1 char is plenty
@CartoType
@CartoType 2 ай бұрын
Any argument which describes people as a**holes has me switching off immediately. Don’t do it.
@the_original_dude
@the_original_dude 2 ай бұрын
whenever I see code with 2 or 8 space indentation, it's always formatted very weirdly, it's like these people are twisted in their head
@redcollard3586
@redcollard3586 2 ай бұрын
First of all, it's not actually funny when Linus says nasty things about **anyone who writes code in even a slightly different style then he does** and it's not actually funny when you parrot it, either. He's been working on his attitude in recent years, because he understands how it has hurt the Linux community. You should participate in that reformation. Second of all, code styles developed in kernel code in C have a completely different set of requirements than userspace code. Any attempted application of one style to the other should be taken with a massive grain of salt. Third, use your IDE to add blank indent markers and they will be easy to see regardless of their width.
@fritzschnitzmueller3768
@fritzschnitzmueller3768 2 ай бұрын
I get it and everything, but if youre in a competent environment, who writes functions with like 8 levels of indentation. Seems like a super constructed university issue
@YouPlague
@YouPlague 2 ай бұрын
Completely misunderstood and misquoted the comment rule though.
@kantancoding
@kantancoding 2 ай бұрын
Seems you’re the one who misunderstood
@zayamoyatv
@zayamoyatv 2 ай бұрын
its always ok to have long functions, long functions makes code more readable
@YLprime
@YLprime 3 ай бұрын
Honestly don't think smart code affects readability, if people can't understand a regular function without max 3 lines of hints, it's really a skill issue on their side, unsmarting you code for people who have skill issues is some really unnecessary work. Not being mean just being real, there is nothing wrong with coding smarter. With all the LLMs going on understanding code shouldn't be a problem.
@kantancoding
@kantancoding 3 ай бұрын
Not sure what you mean by “smart” code here. To me, “smart” code is simple.
@poutineausyropderable7108
@poutineausyropderable7108 3 ай бұрын
8 char is shit. Because good variable names aren't abreviated. So the single if ( LongAssVariableName > SomeOtherVariable && LongAssVariableName < TheWidthOfYourMom.InCentimeters() ) { ... } will be too much to the right. Also, Im shit language like Java where everything is inside a class... Thats 1 less Identation.
@Wutheheooooo
@Wutheheooooo 2 ай бұрын
So you maybe only like scripting languages, because functions as entry point is really important because you can't run code all over the place. So is Java, it just use classes instead, not really different. The C entry point must be a function and called main for example, allow the C runtime to do things before run, even assembly need an entry point.
@Nellak2011
@Nellak2011 3 ай бұрын
func doSomething(animalType string) { if _, exists := animalCounts[animalType]; exists { animalCounts[animalType]++ } }
@poutineausyropderable7108
@poutineausyropderable7108 3 ай бұрын
It actually does animal -> Animal (First letter capitalisation) if Animal[0] > 'Z' Animal[0] += ('A' - 'a'); The lazy C way. Python is just toHigher() Then if exist.
@samuraigaming0
@samuraigaming0 Ай бұрын
tab size 0 is best
@blobthekat
@blobthekat 2 ай бұрын
I am a tabSize: 3 user
@kantancoding
@kantancoding 2 ай бұрын
blasphemy
@reda29100
@reda29100 3 ай бұрын
0:45 let's cut to the chase. How are you going to deal with html and json files then? Scrolling left snd right 5 times a second? Having preferences is fine, but claiming they indicate good or bad behavior (as in bad programming habits) is pure nonsense. They're just conventions, and the only downside is they don't work in the outside world. But within a personal project, or a team which agrees upon those conventions, there is not right or wrong style.
@funkdefied1
@funkdefied1 3 ай бұрын
There is no HTML or JSON in the Linux kernel source code. 98.3% C, 0.7% assembly, and it just goes down from there.
@kantancoding
@kantancoding 3 ай бұрын
Hmm, JSON isn’t code so I don’t really think these rules apply there. And admittedly, I don’t care enough about HTML to go down that rabbit hole 😂
@nerdycatgamer
@nerdycatgamer 3 ай бұрын
you shouldn't be using HTML or JSON. They're both mistakes made up to solve problems that don't exist
@reda29100
@reda29100 3 ай бұрын
Regardless what you think about these things and whether they are up to the task they're allegedly made to solve, they are still standards in the industry. Whether I, you or they like it or not, they (amd other things you don't like in the industry) are a reality that you, I and he will have to adapt to at some point, at least if we were to engage with the wider audience and teams we're not with at the moment. Suppose you're a twch company, need tech workforce, preferably in C, but the entire workforce is too dumb and can only code in [choose a language so that I don't offend you unnecessarily]. And suppose you've been looking desperately for a C programmer for 5 years, and you can't sustain your company anymore (i.e., the ugly reality that json and html are bad solutions and need be disposed of). Do you bet on the utopian programmer that may (i.e., the future in which there would be no json or html, which are the bad inventions the industry adopts today) never come, or adapt to reality, as harsh and ugly it is, and try to make with ehat you got, in the tech workforce market? I don't care if json is the worst thing in the world in this regard. What my point is about, is whther you liked it or not, you have to live with it, and adapt, as long as it is going to be the reality for the foreseeable future. I haven't worked with html or json much, so I'm not dying on defending this hill, and have no dog in this fight. I am just concerned this self-obsessed attitude still lingers in this community. But who am I to envision a society that deviates from normal human behavior? People were, and will ever be believing the sun and the entire universe revolve around their thick skulls. Bit sorry to offend you, and I know I'm just a commenter and you are the one who did the work and made the content, but just have some humility.
@VenusCyberTruck
@VenusCyberTruck 3 ай бұрын
@@kantancoding😂
@canerdemircigm
@canerdemircigm 2 ай бұрын
My code style never will be beautiful I know funct(abc: xyz) { return } funct(abc: xyz) { return } funct( abc: xyz, klm: nop ) { return }
@supericeg5913
@supericeg5913 2 ай бұрын
As unreadable as it is, that while loop is pretty genius though, I didn't know assignments return the read/written value like that.
@giornikitop5373
@giornikitop5373 2 ай бұрын
what if src is bigger than dst?
@gcv6761
@gcv6761 2 ай бұрын
tab tab
@genechristiansomoza4931
@genechristiansomoza4931 2 ай бұрын
Clever code is not useful for work. Not readable in one look. Other devs should be able to understand your code clearly for them to update it with confidence.
@teenriot-de
@teenriot-de 2 ай бұрын
Linus-Rule 0: Insult people that are not your opponion.
@AnythingGodamnit
@AnythingGodamnit 3 ай бұрын
Argument falls apart a bit in the context of OO-based UI toolkits where nesting of components is expected to be deep. Yes, one can break apart monolithic components into smaller ones, but even some of the smallest can have a significant depth to their tree.
@lukaschen6799
@lukaschen6799 2 ай бұрын
Looks like someone never used html😀
@kantancoding
@kantancoding 2 ай бұрын
lol what is html?
@MarcoAntoniotti
@MarcoAntoniotti 2 ай бұрын
M-C-q
@drancerd
@drancerd 2 ай бұрын
This are F# basic stuffs!!! Why and When programming change so wrong?! JS coders F# the programming basics!
@ivankudinov4153
@ivankudinov4153 2 ай бұрын
Hype video without any relevant meaning to its title
@user-lh3xs9km6z
@user-lh3xs9km6z 3 ай бұрын
Fourth ban innocent devs because their nationality ...
@yjlom
@yjlom 3 ай бұрын
that comes from above
@user-lh3xs9km6z
@user-lh3xs9km6z 3 ай бұрын
@@yjlom SO HE SHOULD HAVE HAD NO ISSUE TELLING THE TRITH ABOUT IT INSTEAD OF HIDING LIKE A COWARD... WITH THE BAN LINUS GET THE VILLAIN STIGMA NOW ...
@TheEnmineer
@TheEnmineer 2 ай бұрын
Weren't banned, just were removed from the ability to sign off on their own code commits because of increasing geopolitical tensions. Believe me, it's safer for everyone involved when they can't be forced to put a backdoor in Linux.
The 3 Laws of Writing Bug Free Code
3:59
Kantan Coding
Рет қаралды 85 М.
A New Era for C and C++? Goodbye, Rust?
9:08
Travis Media
Рет қаралды 140 М.
«Жат бауыр» телехикаясы І 30 - бөлім | Соңғы бөлім
52:59
Qazaqstan TV / Қазақстан Ұлттық Арнасы
Рет қаралды 340 М.
Sigma girl VS Sigma Error girl 2  #shorts #sigma
0:27
Jin and Hattie
Рет қаралды 124 МЛН
БАБУШКА ШАРИТ #shorts
0:16
Паша Осадчий
Рет қаралды 4,1 МЛН
JISOO - ‘꽃(FLOWER)’ M/V
3:05
BLACKPINK
Рет қаралды 137 МЛН
5 Signs of an Inexperienced Self-Taught Developer (and how to fix)
8:40
Wisdom From Linus | Prime Reacts
12:18
ThePrimeTime
Рет қаралды 528 М.
Cleaner Code: 3 Ways You Can Write Cleaner Code
7:41
Coding with Lewis
Рет қаралды 101 М.
3 More Laws of Writing Readable Code
4:19
Kantan Coding
Рет қаралды 65 М.
Naming Things in Code
7:25
CodeAesthetic
Рет қаралды 2,3 МЛН
"Clean" Code, Horrible Performance
22:41
Molly Rocket
Рет қаралды 949 М.
Python laid waste to my C++!
17:18
Sheafification of G
Рет қаралды 228 М.
Two MIT Professors ACCIDENTALLY discovered this simple SECRET TO LEARNING
5:10
Transformers (how LLMs work) explained visually | DL5
27:14
3Blue1Brown
Рет қаралды 4,7 МЛН
The purest coding style, where bugs are near impossible
10:25
Coderized
Рет қаралды 1 МЛН
«Жат бауыр» телехикаясы І 30 - бөлім | Соңғы бөлім
52:59
Qazaqstan TV / Қазақстан Ұлттық Арнасы
Рет қаралды 340 М.