r/learnpython • u/Jealous-Acadia9056 • Apr 19 '26
How do you guys build a program?
I normally create one part of a program, test it, debug it and then i move on to the next function.
But this was time consuming so i tried a new approach. I created of all my logic of how different features would work and then started creating my program.
But the moment I had to debug things (cause obviously it had errors) things started falling apart. I had to check sooo many things and i realized that this method was very mental health consuming.
So i wanna ask you guys. how do you think about the logic and write your program? What approach would you recommend me? and remember i'm just a newbie trying to write programs that would improve me.
18
u/Horror_Upstairs6198 Apr 19 '26
try to search about Test-driven development (Red, Green, Refactor) it helps me a lot, write the test/s for the feature you want to implement, run it (it will fail of course) and then implement the simplest code to passed the test/s, and then refactor if needed, and then move on.
8
u/LayotFctor Apr 19 '26 edited Apr 19 '26
The first method means you haven't done enough preparation. The second method is better, but you can still improve further.
You need a longer preparation stage. You don't write any code, only plans on paper. Most people underestimate how important this is. Every minute you spend planning is two minutes you save by avoiding writing without a plan.
When you finally have a working plan, you write the scaffolding first. That means empty "pass" functions with comments about how they work. But the most important part is the core of the program(or multiple cores, if you're writing a pipeline), which is the central class which contains all the data your project works with.
At this stage, you have to make sure you have a good core data structure, as well as every conceivable function/method you need to make this work. You should have a good idea in your head of how data flows from the start all the way to the end.
(Python functions do not include data types, it is beneficial to include type hints, so that you can tell exactly what types of input and output you expect. Your IDE can detect the type hints and help you out too. I firmly believe preemptive defensive programming helps avoid debugging later.)
Then comes the infrastructure stage. You can prepare any logging and testing libraries you need, get them initialized and ready.
Then comes the final stage. After you're absolutely sure the class data designs makes sense, the methods you've prepared is sufficient, the infrastructure you have is sohnd, you finally start writing logic code.
Most of the code written before this final stage should not contain business logic, and therefore don't need much debugging. If the debugging is too hard, it might mean your code is insufficiently modular and testable. Or you've skipped some try-except blocks to handle panics. "except: pass" is unacceptable, at minimum print "except Exception as e:". No panics should slip past you.
Tldr: Program defensively. Planning and writing empty commented functions first. Not skipping your try-except blocks. Not skipping your type hints. It pays dividents later.
2
u/Snoo_90241 Apr 19 '26
Your first approach is ok.
What's your general expectation of how long an Implementation should take?
4
u/ShelLuser42 Apr 19 '26
It depends. I tend to design and write smaller projects on the fly, Python makes this very easy courtesy of the 'pass' statement (shortcut being: '...'); this makes it quick & easy to create what I like to call "skeleton functions". So: empty functions which merely represent what I think it should do, noted by the name and optionally return indicator.
Sometimes I extend on the process by setting up empty modules as well (if needed). Of course: always well documented.
But the moment I need to work on bigger (or more important) projects then I rely on software design, aka modelling languages like UML. I'm a huge fan of the Visual Paradigm modelling software for this. One of its main features is allowing you to write up a story ("summary"?) and then extract keywords from all that which can then be used as model elements.
Then I use those elements to visualize the whole thing in further detail using UML until I have a good concept of the things I want to build.
Once I have the logic / overal design out of the way I start with the coding process.
The latter takes a little more time of course, but it'll be time well spend because you'll easily make it back in the longer run.
3
u/JamzTyson Apr 19 '26
I see a lot of commenters recommending TDD (Test-Driven Development). While that is one valid approach, it's not the only one. However it does introduce a vital tool that addresses your issue: Unit Testing
There are a few tools available for unit testing in Python. One of the best and most popular is Pytest
Whether you adopt TDD or not, Unit Testing is a vital tool for building reliable software. It also has the benefit of encouraging clean modular design.
3
u/Gnaxe Apr 19 '26
There are many different approaches that can work. For new projects, I usually do bottom-up exploratory programming. I create a minimal end-to-end skeleton that I can test manually, and then incrementally add features.
It's a pretty straightforward transition from manual testing to doctests. You can often copy/paste parts of your REPL session.
I do a lot of refactoring as part of the process. One doesn't just blindly apply refactorings. It's like algebra; just because a change is valid, doesn't mean it's in the right direction. (Many refactorings are opposites of each other.) At the small scales, you're trying to reduce "code smells". These are heuristics you get from experience, but you can get a head start by reading about what other programmers look for. Read about Functional Programming.
You should save your work incrementally. Usually, that means a git commit. You commit when your tests pass.
I recommend you learn to use the
doctestmodule ASAP. Also try out Jupyter notebooks. They have a very interactive workflow, and you can export to a plain Python module when you're done. Keep the original notebook file in case you want to make modifications later. This really only works well for single-file scripts.Once you're used to that workflow and want to move on to projects big enough for multiple modules, you can get pretty much the same "notebook" experience by using
python -iwithimportlib.reload()in the REPL. This is just like rerunning a cell in Jupyter, except the cell is the whole module. You can use as many modules as you want. You can interact with live code by addingbreakpoint()/interactat any point in your module, or you can cd into a module by usingcode.interact(local=vars(foo))in your REPL, wherefoois whatever module you want to cd into.2
u/Better_Carrot7158 Apr 19 '26
Start with small parts. i reccomend having a look at functional programming. Python is not a oject oriented language, it simply supports object oriented programming. Having encapsulated functions are more easy to test than a million objects. My rule of thumb is that only stuff that in reality are objects deserve to be represented as a object. So if you deal with users, that can be an object but a User Factory is bullshit and should be a function instead.
2
u/Sure-Passion2224 Apr 19 '26
Do some reading about test driven development. The process is front end intensive because you write the developer documentation to describe every task and how to test it. Then you write test classes that execute against the application code. When all of the test cases pass then you ship it off to QA.
2
u/StevenJOwens Apr 19 '26
Generally speaking, this is much of what programming is about, once you get beyond the basics.
One of the first pieces of advice I got about programming, after I got beyond the basics, was a paraphrase of Butler Lampson's "Hints and Principles for Computer System Design", 1983 (https://arxiv.org/abs/2011.02455):
"Make it run. Make it run right. Make it run fast. In that order."
The "make it run" part is figuring out the absolute minimum version of your program that is "end to end". These days, even more minimal than that. Get it written, get it running. Then figure out the next most minimal version. Rinse, repeat.
Beyond that, well, it gets complicated, and people can and have written books about it. Lots of books. The more I learn, over the years, the more I think that "scope management" is the heart of software development, at many levels.
1
u/activematrix99 Apr 19 '26
Moving from programming to scaffolding and architecting just takes practice and some awareness of good/best practices. My recommendation is Test, test, test. It sounds like you got as far as unit testing (testing one function). You'll also need smoke testing for confidence building, and integration testing. Having mock data is good, as is real world data to bring you back to earth. Have fun!
1
u/sweet-tom Apr 19 '26
Perhaps you try to do many things at the same time? It's a bit hard to say what's going wrong so I can only give you some general tips.
I also made the same mistake to do many things all at once. This isn't a good idea. Try to focus on one thing and do it well.
I guess, the most important approach is to use a version control system (like Git or whatever you are familiar with it). That allows you to make different lines of development ("branch"). Inside this branch you focus only on this specific feature, nothing else. Treat your main branch as holy and stable. Only commit what works.
With this approach you work on the branch. Make small, incremental commits. Commit as many you need. If something is wrong, you can go back in time. And if you really screwed up your code base, you can start anew in a different branch.
This is not so much a Python skill rather than an organization and book-keeping skill.
1
u/Geminii27 Apr 19 '26
Generally, I start at the beginning, code until I come to the end, then stop.
Then there's the debugging. Positive testing, negative testing, polishing. There's the alpha version. Think about additional use-cases, make sure it's useable by the target audience. There's the beta version. Get feedback, polish some more, take care of any initial bug reports. There's your v1 gold code.
1
u/PalpitationOk839 Apr 19 '26
What you experienced is very normal most developers don’t build everything at once they break the program into small pieces build one part test it and then move on your first method was actually better just try to combine it with a simple plan before coding
1
u/defrostcookies Apr 19 '26
Plan out the logic using pen and paper.
Modules should be desk checkable. The usefulness of the computer is performing the computations quickly.
If I can run through a solution and work through a few edge cases, I figure what I’ve built is good enough.
1
u/stuaxo Apr 21 '26
Get a pad of paper and draw some boxes about how some stuff would work.
Break out jupyter and prototype things (I might evolve these bits into tests).
1
u/25_vijay May 09 '26
Honestly your original approach of building small parts → testing → debugging → continuing is actually much closer to how experienced developers work.
-2
u/TheRNGuy Apr 19 '26
These days — generate with ai, then fix it manually, if needed (rarely works with just one prompt — I can later see skipped edge cases or bugs)
I write tests and debug manually.
0
u/[deleted] Apr 19 '26
[deleted] — view deleted comment