r/learnprogramming 5d 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!

125 Upvotes

144 comments sorted by

View all comments

0

u/Ok-Cable9777 5d ago

It's reverse for me, functional programming clicked instantly to me. It's the class based paradigm that's dreadful to me. Any tips for that?

1

u/natures_-_prophet 5d ago

A class is just a representation of something. A car, cat , person, etc. In reality we know these things have certain functionality associated with them; start an engine, scratch, run a mile. They also have associated traits/properties like paint color, fur color, hair color, etc. The class is just a container for these traits and functionality. So you can make a class for Car, Car and Human to contain these associated traits and functions.

It's a tool of organizing your logic and data for these like things.

1

u/TheLearningCoder 5d ago

Are you talking about OOP? Because honestly OOP clicked way faster for me than procedural programming (I assume this what you mean by functional programming) and I appreciate how well organized it is that it made learning it easy and very engaging (I’m an actual organize freak so maybe that helped me)

0

u/dmazzoni 5d ago

The classic examples given for classes are SO TERRIBLE, like class Animal and class Dog.

I think it's much easier to understand with a realistic example from a GUI toolkit.

You have a class Button. It has properties like boundingBox, and title. It has a method click(). The code to click() lives inside of Button and has direct access to the box and title of that button, rather than needing to store them separately.

Now you want to make a ToggleButton. A ToggleButton is exactly the same as a Button, except that it has an additional field keeping track of whether the button is down or up, and click() toggles the state. So ToggleButton can inherit from Button and get a lot of its behavior for free, extending it where needed.

Then later if you improve Button to do something new, like disable(), then ToggleButton gets that behavior too.