In the week 0 walkthrough "cough-4," Prof. Malan defined 3 functions.
Instead we can define 1 -
say word n times and when flag is clicked,
say "cough" 3 times and then
say "sneeze" 3 times! Is this better than the actual program?
CS50 Stack Exchange is a question and answer site for students of Harvard University's CS50. It only takes a minute to sign up.Sign up to join this community
Pay attention to the end of the video, where Prof. Malan explains the purpose of user-defined functions:
... as our programs get much more complicated, and our programs more sophisticated, this technique of ... decomposing your program into smaller functions, each of which call other functions, is a very compelling technique because it will ensure that your code, even as it gets more complex, remains easy to update and also very readable.
This video is a very simple example to show you what can be done. It is not intended as an example of the "best" program you should write. In the end, many of the techniques you will learn are not intended to necessarily make your program run any faster, but to help you and your future colleagues with the general task of writing and maintaining a lot of code.
It really doesn't matter what method you use to make the Scratch cat say "cough" and "achoo" because this program has no real users and no real purpose. When you start dealing with programs where you can imagine real users, real use cases, and a real purpose to the program, you will have the opportunity to justify your choice of how to write the code.
Computer science is all about problem solving. And there are usually many solutions to a single problem.
Yes we could have used a single custom block, passed "cough" or "sneeze" and the number of repeats when calling it and used a loop within the function to repeat that, but for an approach being better or worse than another, this depends on many things.
For example, If I care more about minimizing the number of puzzle pieces that I'm using in my program, I may choose the single custom block approach! However, nothing would prevent me of passing words other than "cough" and "sneeze" and that might be bad for my program if I don't want it to happen!
Of course I may add some puzzle pieces to validate that though!
If I didn't use more puzzle pieces to validate the value passed to the function and I care more about guaranteeing that it's not allowable for my sprite to say anything other than "cough" and/or "sneeze", I may prefer the two-separate-custom-blocks approach. This would be kinda duplicate though since both functions basically do pretty similar job.
And that's always the case with problem solutions in computer science. There's always kinda trade offs, ups and downs, advantages and disadvantages for every solution (call it whatever you want).
How to choose the ideal solution?
As we said earlier it depends on many things including the programmer themselves! You'll learn more about that as you progress with the course!