Flat is Better than Nested in Python, a Practical Refactoring Example



Flat is Better than Nested in Python, a Practical Refactoring Example

Flat is Better than Nested in Python, a Practical Refactoring Example

Join our Community for free: https://pybites.circle.so/
Check out our coaching programs: https://pybit.es

In this video, I show an example of nested data in a function and how to refactor it with early returns or “guard clauses”. We’ve reached less complexity this way and code that is easier to read and therefore maintain.

As the Zen of Python says: flat is better than nested, and simple is better than complex 🐍 😍

Chapters:
00:00 Intro
00:23 Nested code
00:44 Tests
01:09 Inverting conditions (guard clauses)
01:39 Bailing out early
01:56 Running the test
02:05 Doing more of these refactorings
02:50 Final refactoring – flatter code
03:45 Making it even shorter
04:21 Adding another test for edge case
05:01 Conclusion and wrap

Code repo:
https://github.com/bbelderbos/refactoring-examples

If you like this video check out our refactoring playlists:
https://www.youtube.com/playlist?list=PLhaG3iqe9VDbnwM-LA1zkIgBQZFthvHTk


Liked this video? Subscribe for more 🙂

And to get our weekly developer / mindset emails, sign up here:
https://pybit.es/friends/

Comments are closed.