How To Write Cleaner Code - A Practical Example
Vložit
- čas přidán 12. 07. 2024
- Welcome back to another video! In this video, I'll be showing you how to write cleaner code. I'll be going through some script that I wrote a few years ago and clean it up. We'll just be doing some basic things to make the code look cleaner and easier to read.
💻 AlgoExpert is the coding interview prep platform that I used to ace my Microsoft and Shopify interviews. Check it out and get a discount on the platform using the code "techwithtim" algoexpert.io/techwithtim
📄 Resources 📄
Pygame Projectile Motion Tutorial: • Pygame Tutorial - Proj...
Original Code: github.com/techwithtim/Projec...
⭐️ Timestamps ⭐️
00:00 | Introduction & Context
01:26 | Code Output Demo
01:57 | Writing Clean Code!
◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️
💰 Courses & Merch 💰
💻 The Fundamentals of Programming w/ Python: tech-with-tim.teachable.com/p...
👕 Merchandise: teespring.com/stores/tech-wit...
🔗 Social Medias 🔗
📸 Instagram: / tech_with_tim
📱 Twitter: / techwithtimm
⭐ Discord: / discord
📝 LinkedIn: / tim-ruscica-82631b179
🌎 Website: techwithtim.net
📂 GitHub: github.com/techwithtim
🔊 Podcast: anchor.fm/tech-with-tim
🎬 My CZcams Gear 🎬
🎥 Main Camera (EOS Canon 90D): amzn.to/3cY23y9
🎥 Secondary Camera (Panasonic Lumix G7): amzn.to/3fl2iEV
📹 Main Lens (EFS 24mm f/2.8): amzn.to/2Yuol5r
🕹 Tripod: amzn.to/3hpSprv
🎤 Main Microphone (Rode NT1): amzn.to/2HrZxXc
🎤 Secondary Microphone (Synco Wireless Lapel System): amzn.to/3e07Swl
🎤 Third Microphone (Rode NTG4+): amzn.to/3oi0v8Z
☀️ Lights: amzn.to/2ApeiXr
⌨ Keyboard (Daskeyboard 4Q): amzn.to/2YpN5vm
🖱 Mouse (Logitech MX Master): amzn.to/2HsmRDN
📸 Webcam (Logitech 1080p Pro): amzn.to/2B2IXcQ
📢 Speaker (Beats Pill): amzn.to/2XYc5ef
🎧 Headphones (Bose Quiet Comfort 35): amzn.to/2MWbl3e
🌞 Lamp (BenQ E-reading Lamp): amzn.to/3e0UCr8
🌞 Secondary Lamp (BenQ Screenbar Plus): amzn.to/30Dtafi
💻 Monitor (BenQ EX2780Q): amzn.to/2HsmUPZ
💻 Monitor (LG Ultrawide 34WN750): amzn.to/3dSD7tS
🎙 Mic Boom Arm (Rode PSA 1): amzn.to/30EZw9m
🎚 Audio Interface (Focusrite Scarlet 4i4): amzn.to/2TjXsih
💸 Donations 💸
💵 One-Time Donations: www.paypal.com/donate?hosted_...
💰 Patreon: / techwithtim
◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️
⭐️ Tags ⭐️
- Tech With Tim
- Clean Code
- Write Clean Code
- Coding
- How To Write Clean Code
⭐️ Hashtags ⭐️
#TechWithTim #CleanCode
9:40 you forgot to replace newx and newy at line 33
I appreciate code being refactored to a more readable/maintainable state. I am a retired mainframer and once had to maintain a COBOL program written by one with an incomplete understanding of the language. I removed 5,000 (yes, 5,000) lines of unneeded code. The initial program was 50,000 lines. removing those lines improved to maintainability quite a bit. Then doing the other concepts you illustrate made a huge difference.
Tim, the general rule of thumb is to never touch a finished project code which is working fine.
@@8koi139 I just meant it as a joke. You should visit your old code to make optimizations if you are confident you can do it without repercussions and you know what you are doing. But just make sure you have a back up of that code base.
@@coderanger7708 Now you ruined the joke.
@@geoafrikana sorry mate, there was a dude who took this seriously, so I had to explain him/her the real thing to do
I feel like there isn't enough content like this on CZcams, love the pace you go through all of these changes, it's really helpful for me. Thank you!
9:43-10:17 For line 35, it's supposed to be
'return new_x, new_y'
I was looking through the comments like “surely I’m not the only one who noticed he broke his code”😂😂😂 been there
You forget type hints!!, and I think if you had everything separated into functions it would be a little cleaner.
This video was exactly what I needed! Nobody else is doing this. Could you make a similar video about why code needs to be updated, how often etc, with practical examples
He's simply grown as a developer. Updating this code was a great way to showcase some of the tips he has learned in the years since creating the video(allowing you to avoid the pitfalls he fell victim to.) In short, I would say, update your code if you believe it needs to be updated.
ArjanCodes does code refactoring
This is on a whole new level of programming asmr
Thanks Tim. Useful examples, especially for beginners like me
I need to look at your backlog of videos. I found this educational and I didn't get as bored as usual. I sometimes can't focus when learning about programming topics.
Tim, you are the best teacher on youtube.
If you can make a data structure course, this will be helpful.
thank you.
13:46 the problem here is a ZeroDivisionError because it's dividing by (x - pos[0]). It can be changed to the function math.atan2(), which handles the division and zero division errors, like so:
angle = math.atan2(y-pos[1], x-pos[0])
atan2 also allows to skip the quadrant selection below the atan call
Also noting than while the except should have explicitly mentioned the ZeroDivisionError, using a try-except block rather than an if-else block is perfectly fine and pythonic here, and definitively the recommanded way to handle such situations. As one says, "it's easier to ask for forgiveness than permission".
@@MrBanarium But in real world it is not, that has a HUGE performance hit when you are using performance oriented languages. It is a BAD practice to use exceptions for something you could have easily testes. I would NOT hire someone that do it. The "ask for forgiveness" is only good on HIGHER level abstractions, i.e out of the inner loops of the code.
@@tiagodagostini Yes, but we're talking about Python here, which *is* a high level language. In Python, using exceptions like this is recommanded and considered best practice. Exceptions in python are cheap performance-wise specifically because of this.
If you need to hire a python programmer, they need to know the language-specific best practices and features, not just the general dogma, and understand why it's different here. Ignoring python best practice will indeed result in performance loss.
@@MrBanarium true but unfortunatelly the developers take a practice sometimes too much to the heart and do nto stop to think WHY in such a language it makes sense, so they apply it blindly.
Good explaination Tim, though I just wish to share that we can also use black and Flake8 for beautification of code, such as identation, spacing, or unncessary imports. But still defining global variables and function arguments is still someting the programmer has to do.
Thanks Tim! I just realised how bad my code was :)
The try-except case is a really good one to demonstrate the importance of clean code - had you used a more specific exception (ZeroDivisionError), you would have easily known what the error could be there, without having to remember trigonometry! :)
In my opinion the point there might have been slightly missed - it isn't about sticking to best practices with an if-else statement, it's about making the code easier to handle, especially when returning to it after several years
Anyway great vid, love the uploads lately :)
15:50 also forgot to pass golf_ball as parameter in redraw_window().
btw, great video :)
Nice, yesterday I was looking for something about selenium and I seen your playlist about selenium. and then within fraction of seconds I am a subscriber to you.
Thank youtube Algorithms 😁 Tim had nothing to do with it
In our company, in naming variables, we use l (local) or g (global) for variables, plus c/n/d/l (character/number/date/logical type). E.g. lcName, lnAge, ldBirthday, glActive, gcCompany
so it will be easier to distinguish what data type a variable is.
@@mxmdabeast6047 I use vfp though, not python but I think logical and boolean are pretty much the same. The choice of naming convention is yours, depends on what you think suits you best.
A more pythonic version would be to just use the typing system like this instead. name: str, age: int, etc and don't use globals. There is almost always another way.
Loved the video and the resources! Thanks for sharing
Loved this man! Thanks🙌
Keep up the good work Mr. Tim
Very good video! Thanks!
Might be fun to do a type of competition where you ask your viewers to refactor a piece of code like that.
Then we could all learn from the best out of those.
Thanks you taught me a lot of things
thank you for this video it helped me a lot
Thanks for the vid, it helps a lot
even though you forgot like 5 things, you made your point clear and that's what this video is about, so great video
Maybe you could've pointed out that making comments is good practice, also maybe could've said that if you've a lot of and's that you can put them below each other instead of next to eachother and maybe try and avoid if statements, they're not efficiënt and also in a lot of situations not the cleanest solution.
This video is so helpful.
Interesting. Thank you
Super helpful vid!
Well on the context of cleaning the code he have to debug it too 😂😂 as he created some errors while cleaning
Gr8 vid as usual : )
Hey this is great, your code is A++, but another thing to make your code even better is to add a little more comments throughout your exceptional code!😎😇👍✌️😸
Wonderful video, I wonder if you can discuss a better way to address "if elif" and "if if" blocks
good stuff tim !
I am not so bothered by convention but I totally agree with being consistent whatever you decide to use. I would also prefer to have separate functions for the various code blocks personally but as long as others and of course _you_ can understand your code when you have to revisit it to make changes months or even years later that's what matters most.
I agree. I use snake_case for functions and methods, Pascal_Case for classes, just like convention, but I use camelCase for variables. Imo makes it easy to see what everything is, and it also feels natural to me to keep variable names short.
Great video as always! =)
However, I do not like the color refactoring (BLACK, GREY, WHITE).
I would much prefer semantic colors like: COLOR_PRIMARY, COLOR_SECONDARY, COLOR_ACCENT or alternatively COLOR_BACKGROUND, COLOR_LINE, COLOR_BALL.
Imagine you want to update your app’s color scheme and use a green ball. You would have to either change the value of variable WHITE to green (lol) or introduce a new variable GREEN and find all places in your code where you color the ball.
thanks bro 👍🙂
Hey Tim, one question, what made you use Sublime Text instead of VS Code? Great video btw!
Excellent
You're like telling me i have clean code, Thanks man Lol
More clean code videos!
fabulous
Yeah i put notifications on 😎
Dude you are gold for this sphere very very well explained 👍👍 for the young guys don't worry your brain can't take too much unless you are giny who is rare, but who knows anyway gg Timaty 🙃✌
Would to see how to write suitable comments to the code. Also I have been looking alot recently for ways to improve the look of the code so thanks for that. It didn't show me much new but still stuff to improve
Best programming chanellll
Perhaps consider demonstrating mypy (with type hinting) and flake8 from the command line. These are very powerful tools.
But really great work giving some ideas about how to refractor code!
Nice vid, Which video editor do you use??
😂
@@ibijon sublime text is a code editor not a video editor lol
Thanks for an explaination Tim. I like a theme you using in your vscode. Can you share a name of theme Tim?
Make some rust tutorials
agreed with this guy
Cool
Beyond the Basic Stuff with Python: Best Practices for Writing Clean Code (by Al Sweigart) is a really good book for this.
nice
It works 100%
Any book recommendations?
What text editor or ide are you using?
Yei ;)
Beginner here. Is commenting on the code would be seen as bad coding practice? And if not necessarily, what is considered good commenting?
Do you think you could help me with a pycharm opencv project? im not a coder and the code is ready but I dont know how to put it together to run it...
I'm currently working on a puzzle game, which users can grab the element pieces to fill in a grid.
Using the Tetris method to create grid and interface, so far so good, but I cant find any tutorial where I can grab an object (NOT an image) on screen.
How can I drag elements that is in pygame?
I’m not very experienced in pygame, but if there isn’t some fancy way to do it, I’d probably just use the pygame.mouse.get_buttons() method, and move the piece to the mouse’s position while the left mouse button is pressed.
Additionally, you could give the piece a center variable that you update when the left mouse button is pressed (event.type == pygame.MOUSEBUTTONDOWN and event.button == 1) so that it doesn’t snap unnaturally when you press it.
If you need it to snap in place when you release the button, you can do that while handling events: event.type == pygame.MOUSEBUTTONUP and event.button == 1.
9:50 doesnt multiple returned values already get returned as a tuple? I always assumed putting parenthesis was more for just prettier code.
The return on line 33 wasn't changed to reflect the new variable names.
And the program was not run afterwards - Bad Tim, Bad. Love the channel
What's this new theme?
It's cool!
Looks a bit like "one dark pro"?
@@frankanon798 ohk, thanks!
Who is your illustrator who draws the thumbnails ?
they dont draw the thumbnails, they make it with software
What program is he using to use python? For example, is it Spyder or what is it?
did you get a editor ?
One question: in the main loop, don't you need to see first events then movement and visualization?
you should try vim, trust me
I suppose all those missing white spaces and amount of empty lines between functions could be handled with something like autopep8, black or yapf
21:14 I wouldnt put spaces between operators which have priority when other operators present in the same line. So that you can visualize operator priorities. You decide, which one looks better:
b = 2*a + 3
b = 2 * a + 3
@@mxmdabeast6047 In large assignments you can use paranthesis so they dont look strange. Which one looks better:
b = (3**5 * 2) + 7
b = 3 ** 5 * 2 + 7
In the latter one, doesn't "5 * 2" stand out? If you focus on "3 ** 5", doesn't "2 + 7" stand out?
If the assignment is even larger and requires nested paranthesis, maybe you should seperate the assignment to a few lines:
b = 3**5 * 2
b = b + 7
I think these approaches are pretty straightforward. So you wouldn't really think much about whether you should use a space or not. Also, for large assignments, being explicit is always better.
11:54 you forget to replace (0,0,0) by BLACK on line 21
@20:27 could you do: and !shoot
Why not use an ENUM for colours?
I clicked this video and then..... "Do you wanna become a software engineer at Google?"
Me: .....
19:56 couldn't You put "if not shoot:" up in the "if event.type == pygame.MOUSEBUTTONDOWN and not shoot:" like that?
Yes, you could do that. He might have not done that because it's more confusing to read.
If I have a single line after an if statement I write it as:
greeting = 1
if (greeting) : print("Hello")
else: print("Bye")
Is this a good practice?
better to do a proper ternary operator one line if-else statement:
greeting = 1
print("Hello" if greeting else "Bye")
Tuple decomposition? Isn't it called unpacking? :)
For most of these you couda just ran this in pycharm and it would have listed out all the format errors ;-;
This is why you need a linter.
It's better most of the times to use try/except, because of "easier to ask for forgivness than for permission" or something it was going around :)
Check Out the Python black package which helps you to clean code automatically
Sorry, but the first striking thing that this code needs is comments.
You can embellish your code all you like with spacing and snake casing, but comments will make it more readable and easy to understand (and refactor).
Great video, but it might have been a good idea to run the refactored code at the end to show that it still worked. I'm pretty sure you introduced some errors - for example you didn't change all the instances of newx and newy to snake case.
I like camel case way better.... Not sure why python decided to use shake
`import math` should be before `import pygame`, just in case you wanna follow the PEP 8
what is PEP 8?
@@champ_revolutionizer9924 pemdas
So you say camel case is wrong. Interesting facts about "snake case" as you call it. That's just unix style coding and its also used in other languages not just python. The reason it's not so popular is because the _ character on some monitors showed up as a " " character which looks like a space. I used to have a monitor even a few yeaers ago that was new and modern flat screen that did this as well. Using HDMI + tv also can make _ not show at times. So to prevent confusion it's usually avoided.
its what's listed in the PEP8 style guide, not my opinion, pythons style guide...
@@TechWithTimWhat I am saying is that calling it snake case is just renaming something that already exists rather then creating something unique of it's own. In programming, we often have different names for the same thing as people come from other languages. but style isnt exclusively owned by the language itself.
I also noticed the video was lacking other big topics like gaurd clauses verses nesting which have more importance for readability.
i may not be an expert but I have been programming for about 23 years now. i know a thing or 2 because I have seen a thing or 2.
In line 25 you did not change (0, 0, 0) to BLACK :D
You forgot to replace the (0,0,0) at line 25 with the constant BLACK you created.
redraw_window missing 2 positional arguments :)
comments are useful
Forgot to pass the new golf_ball variable when calling the find_angle fuction.
I will never leave camel and pascal case
More things
Always add comments to your methods functions
ball_path should be called path because you are repeating yourself when calling it
Win, pos, vec are not obvious you need to state what these are and how they are used
Your try block should have except Exception as e: print(e) so you know when an error happens
golf_ball could be just ball, as you don't have any other types of balls on the field.
Always copy and paste very names to avoid mistakes Tim made
Always make a backup copy of the file before you refacter
Add comments to complex logic so you can just read why its happening rather than how it happening
run variable is uneeded as you are only using it once
Add comments at the top to what this program does, potential issue and future ideas and also add links to common documents like pygame docs
Your continue block was unneeded and will cause issues later when you have other mouse actions
Add type checks using assert as a sanity check to make sure everything is the excepted type of thing. Especially using tuple deconstruction you will have add errors if pos happened to have a length of three for example.
I typically write all of the function names in the document at the top of the page in a comment so I know what I'm dealing with when I open the project after a long time.
Pretend you are writing the code for a future more retarded version of yourself.
Great and helpful video, could you do a series on creating dapps on the ethereum blockchain?
Instead of doing all this, why not just use a linter like flake8 / black which will fix a lot of the issues you fixed manually
Hi
Snake case for functions? That looks a bit ugly.
You just made it harder for a begineer to understand 😂
Well i just finish 12 hour video when is the new one?