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/jaycrest3m20 Mar 30 '21
Pre-optimization is a programming sin.
Generally, at the beginning, you are gonna throw down 90 lines of code, and then start organizing. After enough experience, you are going to recognize patterns and pre-plan the code for those patterns.
Writing down comments for functions you need and how they should work is a really good idea, I think. Feel free to change your mind part-way through the code if some other design pattern emerges.
Avoid having a function that does too much. For example, instead of having a single, monolithic function that reads from a file and writes to a database, make two functions that each do one job, then make a third function that simply calls those two other functions. In this way, things start building up like Lego blocks. This way, your third function has an option of calling different read and write functions, depending on what is needed, freeing you up to think about more important things.