Spotting Code Flaws
00:00 Spot Flaws in Your Code. Refactoring your code contains the risk that it’s a never-ending endeavor. Like a drawing where you keep erasing to perfect your line, you could spend unlimited time looking for improvements in your codebase.
It’s a good idea to limit the scope of your refactoring process. You can do this by glancing over the code and listing the flaws that you want to erase. Don’t be intimidated. In general, the code is viable, and it works. However, as you discovered in the last step, the
forward_to_target_url() functions in your
main.py file aren’t ideal yet.
00:41 Feel free to revisit your code for a moment and write down any shortcomings that you find. Then you can compare your list of items with the ones that you’ll find here.
Start by having a look at the current state of
In line 41, you’re hard-coding the alphabet as a value of
chars. If you also want to add digits to the string, then typing them out can be cumbersome.
You may have heard of the Don’t Repeat Yourself, or DRY, principle for keeping your code clean. Lines 42 and 43 look nearly identical. The way that you are constructing the
secret_key variables is a perfect example of non-DRY code. In lines 44 to 49, you are interacting with the database.
This action should not be a direct concern of
create_url, you want to define what data your endpoint expects and what the endpoint should return. Ideally, you should outsource any computation of your data to other functions.
At the end of the function in lines 50 and 51, you are mingling with the database object to create the
schemas.URLInfo response. You’re not trying to save this part to the database, so there’s no harm.
But there should be a more apparent separation of the database interactions in the lines above. In summary, the
create_url() function is too loaded with different actions.
02:09 When you’re reading the code, it’s hard to understand the function’s purpose.
Next, let’s look at
forward_to_target_url(). Again, take a moment to pause the video and find the problems on your own before watching the rest of this section.
In lines 61 to 65, you perform a database action. Just as in
create_url(), it doesn’t feel right that you interact with the database in the function that defines an API endpoint.
In the next section of the course, you’ll take the flaws that you found in
forward_to_target_url() and fix them one by one.
Become a Member to join the conversation.