#Python #VBA #Functions #Procedures #MainFunction #CodeOrganization #CodeEfficiency
Are you a newbie in the coding world and wondering why it is better to use functions/procedures instead of just dumping everything into main()? 🤔 Don’t worry, we’ve got you covered! In this article, we will discuss the benefits of separating your code into sub procedures or functions rather than keeping everything in the main block. Let’s dive in and explore the reasons why it’s important to structure your code properly for better efficiency and readability.
## Benefits of Using Functions/Procedures
### 1. Modularization
– When you break down your code into smaller, reusable functions or procedures, it becomes easier to manage and debug.
– Each function can be designed to perform a specific task, making your code more organized and structured.
### 2. Code Reusability
– Functions or procedures can be called multiple times from different parts of your program, saving you from writing the same code again and again.
– This promotes code reusability and reduces redundancy in your codebase.
### 3. Improved Readability
– By using descriptive function names, you can easily understand the purpose of each function without diving into the implementation details.
– Functions make your code more readable and maintainable, especially for others who may collaborate on the project in the future.
### 4. Testing and Debugging
– Functions/procedures can be unit tested independently, allowing you to identify and fix bugs more efficiently.
– Isolating specific functionality in functions makes it easier to pinpoint errors and troubleshoot issues in your code.
## Example: Main Function vs. Separate Functions/Procedures
Let’s compare two code snippets to demonstrate the difference between dumping everything into main and using separate functions or procedures:
### Main Function Only:
“`
Sub main()
Everything here
End sub
“`
### Separate Functions/Procedures:
“`
Sub main()
Call calculations
Call report_gen
End sub
“`
In the second approach, the calls to calculations and report_gen are encapsulated in separate functions or procedures. This not only improves the readability of the main block but also allows you to focus on specific tasks within each function.
## Conclusion
In conclusion, using functions or procedures instead of dumping everything into main has several advantages in terms of code organization, efficiency, and maintainability. By breaking down your code into smaller, modular components, you can improve the overall quality of your program and make it easier to manage in the long run.
So next time you’re tempted to clutter your main block with a sea of code, remember the benefits of using functions/procedures and consider restructuring your code for better efficiency and readability. Happy coding! 💻🚀
If you found this article helpful, be sure to check out our website for more tips and tricks on coding best practices and software development. Let us know in the comments if you have any questions or additional insights on this topic.
Happy coding! #CodeBestPractices #SoftwareDevelopment #CodingTips
When starting out it’s simple and easy to put everything in your main(). However, as what you are developing gets larger and more complex, this approach becomes unmaintainable. Imagine a system with 10 million lines of code in a single main(). It would be impossible to understand and make changes.
Does your home have cupboards, drawers, wardrobes, shelves, bookcases, etc?
Why? Couldn’t you just dig a big hole and dump everything in there? Well, you could! If your house is small and you don’t own many things you can just keep a pile of all your belongings in the corner and it’ll work fine.
A lot of the complexity in our programming languages come from trying to organize code. It’s usually a good thing to be able to put code for one thing in one function, and code for something else in another function. Then you might want to start grouping related functions into files, and putting things together into programs or libraries, and so on.
Of course, you can have too much, and there are extremes. There’s no point in putting each grain of rice in its own box… and similarly, you can definitely take simple code and make it complicated by just splitting it into lots of functions.
It’s probably good practice to try split things up into functions as much as you think you can, as it’s harder to do too much than it is too little.
imagine there are 100 other things happening in that main file application, then your report format needs change. so you have to change it, but reports pull info from all over the application so your report code is mixed in with all the other business logic. so you have to change all of it. and that might break other things. by comparison if report_gen is its own function that is just interfacing with the rest of the services, changes to your reporting requirements will only require that module be changed, and the rest of the code will be separate and uneffected.
And if you have to use the same block of code twice, you’ll just copy and paste it? And what if you don’t even know how many times you need to use this block of code?
It is easier to test smaller pieces of code.
Do you never get the idea “hmm, I need to do something here and I have already done that exact thing elsewhere, it’d be nice not to have to write the same exact code twice”?
when u want to add functionality to the code incrementally, u will get headache trying to piece back the program properly in your head …
it means the program is more difficult to maintain. U usually dont do this, unless it is unavoidable, some programs are really complex and have to do a lot of different things at the same time ….
If you get a job writing software, you will end up working on a project that contains so much code, you will not even be able to fathom reading all of it. For the sake of argument, let’s say 10 million lines. Why would you want 10 millions lines of code inside the main() function (with various if statements, loops, etc.), instead of trying to reasonably organize it into separate files, function calls, etc.?
​
>my programs are not that complicated
If your programs serve any “general purpose” that’s meant to be used by other people (especially non-technical users), they’re basically guaranteed to grow and become pretty complicated. If these are just simple programs that only serve as personal tools, do whatever you want (I have a lot of scripts and such that are like this).
The smaller you can get your parts of code the better to troubleshoot or change or fix. You might get to a point where everything feels too small but that is likely the point that you made your changes the smallest they should be.
Oh, get an open air account or Claude feed it the code you have in main and ask it to break it down. It won’t be perfect but it will help you to see the smaller parts in refactoring your code.
It’s like reducing a cooking recipe to its core ideas:
“`
int main() {
clean()
prep()
cutEverything()
cook()
combine()
bake()
finish()
returnCode = test()
wash_up()
return returnCode
}
“`
The recipe is ofc more complex than this but having it this way is not only an easier way of breaking-up the problem, but also at a glance you can tell what’s going on throughout the life cycle of the program.
This has been reduced beyond even pseudo code, but it’s just to demonstrate. You keep the more “granular” implementation details separate. Suppose this is for a specific recipe – suppose it’s to execute arbitrary recipes. This is heavily abstracted, but it has way more versatility now.
Separating code into functions isolates it from everything else. It establishes the code as a box with defined inputs and outputs. This allows you to work on and debug it in isolation without breaking something else.
Have you tried maintaining and debugging a program with over 1000 lines of code that has all its logic dumped in a single main function?
Organization purposes.
it’s easier to seperate things.
of course, if all your system does is calculate addition and subtraction and nothing else, you will be fine by putting all in main.
But if you have a larger system (OR you dont know how large your system might end up being) its smarter to seperate things out in files/folders, so its easier to find a specific thing later, when you need to update or fix it.
having 9000 lines of code in the same file, is annoying to scroll through. its difficult to get a good overview.
same thing with LONG functions. Splitting functions up (where it makes sense) is also a good habit. It’ll be easier to read the function and understand what it does.
On small scale like excel macros – it’s mostly reusability of some pieces of code. On large scale it’s totally different thing, it would be crazy hard to write and maintain real application written as one function
Here’s the reason you like to put code all in `main`. You don’t understand function parameters and don’t know how to use them. You also figure, if I don’t have to use it, then I won’t.
You would never get a programming job without knowing *how* to write functions.
Also, it’s easier to debug a function than all of main. A 20-line function can be checked more easily than a 200-line main.
For the most part, its about organization, readability, and repeatability.
If you have an algorithm that sorts an array. Making a function called sort that abstracts the several lines of code required to sort down to a single word, then reusing it several times is just cleaner.
There are some rare cases where using a function that does something simple like a single addition or multiplication many times can impact performance due to the overhead of calling a function, but it’s almost never worth considering
Thanks everyone. I am convinced the later is better.
If your programs are pretty simple then the only real reasons to use functions is to practice their use. Once your programs become more complicated they will eventually be completely unmanageable without splitting them into functions.
as soon as you’ll start dealing with software in the real world (which at minimum will be dozens of thousands of lines) you will quickly realise that this approach won’t work.
Subroutines are effective for eliminating duplicate code and isolating bugs. I wrote a program that needs two variables supplied. I have 8 other programs that just so happen to be able to supply two variables. So yeah I could have had 8 larger programs, but now it’s 8 very small programs and one medium program. No duplicated code.
its so much easier to fix when things go wrong. if its a problem with a function you just fix that function instead of diving into main() and trying to figure out what small thing is messing you up
Key concept: orthogonality (i.e., perpendicular in many dimensions).
[https://www.freecodecamp.org/news/orthogonality-in-software-engineering/](https://www.freecodecamp.org/news/orthogonality-in-software-engineering/)
In very simple terms, the moment you have to do some work (multiple lines of code) more than once, you should break it out into a separate function, rather than copy/paste it. The reason is, when you eventually modify that code, you only have to *do it in one place* rather than do a global search/replace (which would be more error prone). Now, when you’ve improved or corrected that one function, every section of code that calls it will automatically benefit.
To prevent that really dumb programmer from reading that code and not understanding a thing.
That really dumb programmer is you in two months.
Because of the international software standard. If we don’t follow the professional standard procedures the algo will look like a spag, it will be less-readable and not time efficient. More of, you are now violating the Three rules which means:
KISS – Keep It Simple Stupid
WET – Write Everything Twice
DRY – Do not Repeat Yourself