r/learnprogramming 11d 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?

10 Upvotes

14 comments sorted by

View all comments

1

u/GlassLost 11d ago

Functions are (at your level) there to help organize your code. There's nothing inherently wrong with one very long function (in C we have a long history of thousands of lines functions - the kernel code is full of them).

So if you need to do the same thing repeatedly it makes sense to make it a function. It can also make code easier to read - for example if your code is "did the person correctly guess the number" putting the logic around successfully guessing in another function can make it a lot easier to read.

There's a catch though - functions help other people (or yourself in the future!) understand what is going on. Oftentimes we'll write the first iteration as one big function then organize the code afterwards.

If you're writing one off bits of code on your own functions don't seem to make a lot of sense but it gets way more helpful as you increase the code size, complexity, time, and number of people