Mastering PyCharm Transcripts
Chapter: Refactoring
Lecture: Creating constants

Login or purchase this course to watch this video and the rest of the course contents.
0:01 Let's look through our little application here, it's quite simple, we have our main,
0:04 it prints out the header it prints out the game loop,
0:07 but the header part, it's kind of hard to see,
0:09 it's this cool dragon thing that I added, just some ascii art.
0:12 but maybe we could make this a little more maintainable
0:17 because this is kind of a problem, like I'd like to put this aside
0:20 and just say okay, give me the text that is a little dragon picture, all right.
0:25 So what we can do is we can come over here and highlight this
0:30 and we can say I'd like to extract, it could be a variable,
0:35 I guess it could be a parameter or a field, but let's say constant.
0:39 Now, in Python, constants are really conventions,
0:42 there's no language mechanism to make a variable technically constant,
0:47 so the convention is to make the name of the variable all upper case,
0:53 so when we say extract constant, we get something like this,
0:57 and let's scroll up if we can without messing this up and see what happens.
1:00 So we put it up at the top, there's this thing called S,
1:04 and look, here's our string, so we'll go back down here
1:07 and we'll call this DRAGON_TEXT and of course, up here it's naming it DRAGON_TEXT.
1:11 So now if we look at our print header,
1:14 okay we print out a new line, dashes, DRAGON_TEXT, dashes,
1:19 we could even make that a constant,
1:21 so if we change it, it changes only one,
1:24 truly it's just using these two places like two lines 30 and 32
1:28 so let's not worry about it.
1:30 But it's really cool how we can extract these constants,
1:33 we could do the same for here, we could make a constant
1:35 and if we replace, notice it will find all usages of it
1:42 maybe we want to tie this to the dragon or wizard,
1:45 maybe we don't, because it's not related, this time it is not,
1:48 so we'll say the level where did it get that from?
1:52 Let's call this starting hero level, make it nice and explicit,
1:58 where did it get the level from?
2:00 It's got it up here, it got it right from there, that's pretty awesome, right?
2:06 So I just go in some random number it's like
2:09 hey this number here represents the parameter
2:12 being passed to the thing called the level, so let's guess that, that's pretty sweet.
2:16 So we can use this extract constant thing
2:19 and these typically go at the top of the file
2:21 so right here we can configure a few things at the top and then play our game.