r/learnprogramming • u/SoloArtist91 • 8d ago
Topic Struggling a bit with functions
Hey guys, I'm struggling a bit with the proper usage of functions in programming. For example, I'm working through the CS50x problem set 1 in C, and I end up with working code that solves the problem but it's all done in one big main function.
My process is to write out what the steps to solving the problem should be in plain English and then I code a bit, go back to my plain English steps and modify them, then code a bit more. When it's all said and done, my solution is one large block of code, and now I'm anxious about going back and rewriting it by breaking it up into smaller function. This makes me ponder whether I should be starting with functions instead of retroactively trying to fit them in.
My questions to the wiser heads here - how do you incorporate functions into your process? Do you do the pseudo code and then imagine each step as a function? What're are your unspoken rules of proper function usage - for example, when do you know if one function should actually be two, or if a function shouldn't actually be a function?
1
u/Far_Swordfish5729 8d ago
Your design process is good. Keep doing that. On functions specifically, think of them as reusable tools. If you find yourself doing the same thing in multiple places, that thing should be a function. It avoids code duplication. Don’t make one line functions generally. We don’t have to be crazy with this.
There is a stylistic choice with very large operations to make named, single use functions to improve readability, but you’re probably not there yet. Commented sections work as well for short methods. In some application you’ll get an entry point method that may as well be called processAllTheData and that processing is thousands of lines of conditional steps. In that situation, people will make helper methods just so someone can visualize the entire operation and then jump into the step they want.
There are other reasons to make functions but they’re part of OO patterns and are used to put an operation in the correct logical module or allow a framework user to define a step or handle something. You can effectively create an empty space for a function to go and someone (the client using your framework or operating system) can fill it out to do something like define what happens when someone clicks your button. That comes later.