#100DaysOfCode in Python Transcripts
Chapter: Days 34-36: Refactoring / Pythonic code
Lecture: Refactoring 10: quality code best practices
Login or
purchase this course
to watch this video and the rest of the course contents.
0:00
Alright number 10, bonus, the last refactoring item.
0:03
I'm just going to talk over some
0:05
general coding best practices
0:07
because of course Pythonic code is important
0:10
and pleasant to read but it's often also a matter
0:13
of sticking to the best of role coding practices.
0:16
For example, make sure your units of code are short.
0:20
Typically, a function or method should
0:23
be around like 10, 15 lines max.
0:26
It can be very Pythonic but if you start to
0:29
write functions of hundreds of lines of code, it's not good.
0:32
It's not easy to maintain.
0:33
So this is your 10 guidelines to make
0:35
your code more maintainable.
0:37
Some other ones I want to highlight here,
0:39
write code once duplication is a monster.
0:42
You really want to prevent having
0:44
the same code defined in multiple places.
0:47
Keep unit interfaces small, so that
0:49
means when you have functions the number
0:51
of arguments to get if you keep that to a
0:54
reasonable level, it's easier to maintain.
0:56
For example, if you have a function that
0:58
takes 10 arguments, not easy to maintain.
1:01
You could consider passing around a
1:03
class or refactoring to a class modules.
1:06
Again, that's the part of name spaces of the Zen.
1:10
It's good to have similar behaviors
1:12
or similar objects grouped together in files.
1:15
To not have one file holding 10 classes,
1:18
split those out in files, right?
1:20
Which makes it easier to reuse them in other programs.
1:23
Testing of course, you want to automate your testing
1:27
that when you make changes you have this regression
1:30
suite that you can just run in seconds
1:32
and highlight if you introduced a new failure.
1:35
Which, if your system becomes more complex, might happen.
1:38
This is an automatic way to catch that
1:41
and keep the quality of your software high.
1:43
In day 10 you learned about pytest
1:45
and how to write tests so that's really important here.
1:48
There's also a lot of habit around this
1:50
so if you get into the habit of writing clean
1:54
code, keeping to high standards, it means
1:56
that when you go into your code base, you leave
1:58
the campground cleaner than you found it, right?
2:01
I love the anology in the pragmatic programmer
2:05
book about having a small crack in
2:08
a window if I remember correctly?
2:10
Leaving that unattended leads to broken windows
2:14
and the same is true for your code base.
2:16
If you let small bad habits creep in
2:18
it might actually lead to a lot of damage in the long term.
2:21
It's really about having good habits
2:24
around writing clean code, run the PEP8 checker
2:27
on your codes, see if it's formatted properly,
2:30
the right conventions are used, etc.