r/learnpython • u/brushygiraffe • Mar 30 '21
How are you ‘planning’ your code?
There’s a thousand videos on Youtube on how to code Python - but they seem to be more like function references - which you can look up in the documentation?
How you guys and girls think through what you’re about to write?
Should I write 90 lines of code then reorganise it into functions? Or start writing functions and then finally ‘use’ the functions at the bottom of your code/script?
Is there a best practice way of doing this? I’m trying to make it easier for myself so everything works like ‘lego’ - otherwise I find I get really confused
Should I write down the steps as comments and then fill in the code after?
‘’’ getjson() Function will accept json string and return TSV def getjson():
‘’’ getinputs() function will read argv[1:] and return the first parameter, or exit with error message if none specified def getinputs():
‘’’ writetosql() function will accept TSV and write it to final.db def writetosql():
‘’’ Run the functions inputs=getinputs() tsv=getjson(inputs) writetosql(tsv)
1
u/DrMaxwellEdison Django and stuff Mar 30 '21
Big libraries that everyone uses with complex algorithms and data structures were not written top to bottom that way. We build what works with good intentions, we find flaws in our designs, and we iterate.
If I have a script that does a sequence of events one time only, that can stand on its own.
If I find I need the functionality of that script somewhere else in a program, I wrap the logic into a function and call it. The script can still work as it did, and I can reuse that effort.
If the same function needs to be used in a slightly different manner, add some optional arguments, adjust the logic so it can do both, and keep it going. Write automated tests to ensure that logic works both ways so you have confidence in the results, then move on.
If I find I'm passing around a lot of common data, or there's a complex set of arguments that usually go together, I might then design a class to contain that data and related logic.
Sometimes I'll start diving into a problem that's secondary to the problem I want to solve and then I have to ask "did someone else already solve this?" Then it's time to go searching for helper libraries, SO answers, etc., to speed up the process. Even when those solutions are too generalized or not a perfect fit, I can adjust it to fit my needs.
So, how do we think through what we're about to write? Honestly, that's a trick question, because there is no "about" to write: I just start writing it, knowing I can refactor it into something workable later.