Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Improving the App's Design With Refactoring

00:00 Time to refactor generate_dice_faces_diagram using the extract method. You apply this technique by extracting functionality in a larger function that can serve as an independent function.

00:11 You’ll be extracting the first two steps of generate_dice_faces_diagram into their own non-public helper functions. You can define these right after generate_dice_faces_diagram.

00:21 The first will be _get_dice_faces accepting the parameter dice_values.

00:28 You’re probably wondering about that underscore because Python doesn’t support the distinction between public and non-public functions. We’re following convention here by adding a single underscore at the beginning of the function’s name.

00:38 Other Python developers should hopefully know to treat this function as non-public, meaning it shouldn’t be accessed from outside of dice.py.

00:48 And for the function body, you can pretty much cut and paste from the original diagram function.

00:59 Okay, and the only thing you need to add is a line at the end to return dice_faces.

01:06 Next, we’ll extract generating the dice faces rows: def_ generate_dice_faces_rows, taking the parameter dice_faces.

01:16 And again, you can cut and paste. Take everything from that second section with the comment, generate a list containing the dice faces rows.

01:28 Again, just adding the line return dice_faces_rows.

01:32 And now you just have to re-implement the functionality by calling your helper functions back in the original diagram function. Get rid of these comments:

01:43 dice_faces = _get_dice_faces(dice_values) dice_faces_rows = generate_dice_faces_rows with the argument (dice_faces).

01:56 This is much easier to read, and also a more declarative style. You’re free to change the implementation of either of these helper functions, and so long as they keep the same interface, that is, retain their parameters and return values, the diagram function itself will remain unchanged.

02:12 Now it’s a good idea to save and test that the app is still working correctly. python dice.py, How many dice do you want to roll? Let’s try four. Perfect.

02:24 There’s nothing left to do but wrap up with the summary. Oh, and if you notice the lack of puns in this lesson, it’s only because I wanted to keep the focus on dice rolling instead of eye rolling.

02:36 I never meant to dice-appoint you.

Avatar image for Vicente Hernandez

Vicente Hernandez on April 19, 2025

What a good lesson, Focus on dice rolling instead of eyes rolling… Never ment to diceapoint you! Haha Really Funny! Man, that will have me laughing for days!

Become a Member to join the conversation.