I can’t really wrap my head around OOP. Like I understand an array and a function and a variable, but I don’t understand what an object is. Why can’t we just use functions and variables everytime we need information or code to run? I code in Python and JS mainly, so objects are truly the most important thing, but I don’t really get it. Also, isn’t every program object orientated? Even C, does it not fit the definitions? If so, how is it any different from C++?
In: Technology
The coolest example is [the observer model](https://en.wikipedia.org/wiki/Observer_pattern#:~:text=In%20software%20design%20and%20engineering,calling%20one%20of%20their%20methods).
If you want to have several threads (subroutines of a program running simultaneously) interacting with a variable in functional programming you would have to keep checking if it changed, since the variable can’t really communicate with the rest of the program.
In OOP you can make the variable into an object class. It can have various properties based on functions that said class contains. You can make things public to the outside, or hide them.
For example, one of the tools in OOP is the function that initiates the whole thing. Within that function you can check if another instance of this class exists, and if it does, you order it to commit sepukku. This way there is only one instance of this class within the whole program, even if you forget about it, or share the code with someone else. (This is called a Singleton)
The variable access is locked to the outside (at least that’s the general consensus), so you can’t just write ThisIsINT = 4; you need to politely ask the class to do it for you. So you add a function that changes that variable and then you call the class function (if it’s public) by writing ClassName.ChangeMyINTPlease(4);
Here’s the fun part. Even if you use the class only to store that one value, nobody can stop you from making it announce to the world it has changed. Within that function you can call a different one that alerts other classes that the value has changed. You can even add a popup window with “I’m 4 now!” if you want to.
So the whole observer model relies on classes calling a function that saves the ID of those classes within the observed class, as a list for example, and then you can alert them when things happen. It can be a singleton, but it doesn’t have to be. If you want to have a function that returns the value of that variable multiplied by 3.47, you can do that.
All of it is saved as a class, and whenever you create an object of that class you can expect it to always behave the same way. And if you use a class written by someone else, you receive a box with bunch of holes in it, the author then tells you “if you want the box to do some cool stuff, then throw an apple into this exact hole, if you use any other, it will explode”
Latest Answers