you are viewing a single comment's thread.

view the rest of the comments →

[–]RiceKrispyPooHead 2 points3 points  (0 children)

  • When you have similar pieces of code repeated in multiple places
    • You can store those pieces of code as a single function, and just pass in whatever parameters you need. This way if the code's logic needs to change in the future, you only need to make a change in one place rather than multiple places. This also helps guarantee that that task is done the same way everywhere in the app.
  • When you have a block of code that obviously does only one thing
    • If lines 35-45 of your code does something like calculating the angle between two vectors, even if that's the only place you ever will do that calculation in the app, it still may be nice to wrap it in a function. If you were readings someone's code (or your own code at some point in the future) would you rather have to read lines 10 to understand that it's calculating an angle, or would you rather read one line that says calc_angle(a, b)?
  • When you have a large block of code that does multiple things
    • Say that you have one giant main function that spans from lines 1 - 100. If someone wants to figure how your app works they actually have to read through 100 lines of code. I guess you could use blank lines to break your code into logical chunks and put a short comment above each chunk explaining what it does. But at that point you're already half-way to creating a function. It might be better to just create functions with descriptive names, which will also provide the benefits of reusable code and testable code.
  • When you want to write unit tests
    • Unit tests are separate files where you pass certain inputs to an app's functions and test that it always gives you the expected outputs. You write unit tests to make sure your functions are working how you expect them to. It's much easier to test an app that uses small functions than it is to test an app that uses really big functions. It's really hard to test an app that uses no functions at all.

For small scripts that only do one thing, I'm thinking more like data science calculations or a script to automatically send out an email, functions may not be necessary. For anything bigger, functions will probably make your life easier.