Refactor Your Code
00:00 I’ve got a chance to make my point about mutable lists and we have a working program that even fixes a little bug that was in there that you may or may not have encountered because maybe you’ll just always create one poem and you would’ve never run into it.
00:14 But in this lesson, you are going to look at one of the most important and somewhat final steps of when you’re writing a program, which is think about what you did and refactor to make it more coherent and simpler, more understandable and better readable.
00:33 So I was playing around with different ways of picking out these random words from a collection, but if you’re actually going to write this program, it would be probably best to just stick with one.
I don’t even need all these code comments anymore at this point. I feel like I can completely get rid of them because the code is quite self-explanatory. I’m using the
random module, I’m using the
sample() function, and it tells me how many I’m picking out by just looking at the
k parameter over there.
All right. I will stick with doing adverb
random.choice() instead of
random.sample() because I know I just need one. So that’s also like more descriptive here that I’m only going to pick one and I don’t need to deal with the nested list afterwards.
02:48 One more thing this allows me to do, because I’m not mutating the lists anymore. I can also get rid of needing to deep copy the words to pull. I can just delete that, don’t have to worry about it and get rid of an additional import that I’m not using anymore.
And by refactoring the part about picking the words to use, we cut down a lot of lines of code. We made everything work similarly except like one time we use
choice() instead of
sample(), but it makes it more straightforward to keep an overview of what you’re doing in here.
04:22 I’m going to add a new line at the beginning and one at the end. That’s just going to be part of the poetic structure of this construct here. Let me run that again and you can see it’s a bit easier to read.
04:40 All right, this looks better. And this is, in a way, you could think of it as an unnecessary step because the poem generator was working before. We didn’t change anything about the output, but you change some things about the internals, which makes it easier to read faster and less complex.
04:59 All of these things are super important for writing code. I like to have this last step of looking at the code again, figuring out what did you learn in the process of writing it, and then apply the best thing that you’ve found.
05:13 There may be other ways of doing it that are even better, but in your process, you found out one way that works the best, and then you just want to apply that one consistently and clean up your code to have a nice script that you can also imagine maintaining into the future.
Become a Member to join the conversation.