r/learnpython • • Nov 05 '20

How does one learn to make well-structured programs? Mine are dumpster-fires.

So I just (kind-of) finished reading Automate The Boring Stuff With Python, and for the past month I've felt like a big-brained super-hero automating myself out of a job (Data Analyst).

The problem is, I feel I missing something along the way. I don't understand the proper way to use functions, what a class is, why people have multiple files in a program, how/why people use GitHub...probably some other things I haven't discovered yet.

They all seem to be related to organization? Is there a "How To Structure Your Python Stuff With Python" book?

478 Upvotes

98 comments sorted by

View all comments

370

u/pbw Nov 05 '20

There is an art and science to programming that must be learned that’s totally independent of any specific language. It takes time and practice and study.

You need to develop an engineering aesthetic so when you look at code you immediately see how it could be improved. Then you need the skills to push it into that shape without breaking tests or functionality in general.

There are books you can read but it’s somewhat like reading a book on how to play basketball. It can give you ideas but you have to practice it yourself, figure out your own ways of looking at things and doing things.

In writing (English) they say everyone has 100,000 words of poor writing in them. So the best you can do is speed through that to get the good stuff.

78

u/TheGrapez Nov 05 '20

This is oddly inspirational thank you!

27

u/Solonotix Nov 05 '20

Some tips: consider cyclomatic complexity. This is a fancy way of saying "How hard is it to understand what can happen?" There are formulas that can calculate roughly the cognitive burden of understanding code, but the simple take away is this: each if counts as 1, and every nested level adds a multiplier of 2n where N is the number of nested levels.

So code that reads if(if()else if(if()) else... would be 11 (if my math is correct). Depending on what you're writing, set a limit on this value (probably 6 to start). If you go over this, you should probably break the logic into parts, and make those parts functions, or class methods, depending on the type of work you're doing. This won't simplify the action, as these steps are still being performed, but you can at least better understand what each step does in a vacuum.

Another good practice is to start with your intended result, in the form you want it, and then work backwards until you connect that logical goal to your logical start. Working with a friend who is learning some rudimentary programming in school, she frequently struggles with visualizing the final data structure she wants, so I figured I would call that out. Doing this frequently reduces the number of intermediate steps you need to do.