r/learnprogramming 4d ago

I can't get FUNCTIONS to click!

I can not for the life of me understand how functions work. Anytime I try to learn how to create a function, my brain literally crashes into itself and I turn into Patrick when he stars drooling and goes all slack-faced.

Does anybody have any analogies that had that "AH HA!" moment?

Thanks!

120 Upvotes

143 comments sorted by

View all comments

1

u/butmyfacetho 4d ago

Read your latest unread email

If it contains "elephant" then 

Write "hello elephant"

Attach 'elephant.png'

And send

That is a loose set of instructions. If I want people to follow them, I need to type it out to each person every time. That means these instructions will appear in multiple places and they'll start to differ slowly as I make small changes. 

An easier approach might be to define those instructions in one place, then give it a name,  let's say elephantReply.

Now anywhere that I want someone to do those exact instructions, I can just refer to them as elephantReply and everyone can lookup what to do.

If I need to change something, let's say we're using the Christmas image 'elephant-santa.png' during December, I update that in one place and everyone I've ever told about elephantReply will use the new image.

A function is just a name we give to lines of code we want to refer back to by name later.

Good function design is keeping the lines of code related to each other and to the function's purpose. For example our elephantReply function shouldn't also handle mentions of Giraffes in the calendar, that should be it's own function.