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
You absolutely can just use functions and variables. However as your program gets larger and more complicated, things tend to get messier.
Say you are programming a car in some sort of driving game. You could start with a string for the car’s name, an integer for its speed etc. Now you want to add another car. You could do it again and now have variables named things like car_1_speed and car_2_speed. Obviously though it’s not scalable to do this for hundreds of cars though.
So you can turn to something like embedded lists or a dictionary data structure. This cuts down hugely on how much repetition is in your code. And it is perfectly feasible to have a list with each item a car that is itself a nested dictionary of all of its variables.
However now you start writing functions. You need to have car_accelerate which edits a car’s speed. Maybe car_horn that plays a certain sound given the car_horn_type it’s passed. Where are you putting them? Just top level of your document will work, but then you also need to create a nested dictionary for drivers and all the driver functions. And race courses and race course functions. You can use comments and spacing and even separated files to try and keep things organized, but using objects lets you group things together.
The car object will have variables called attributes as well as functions called methods wrapped up nice and neat inside of it. Now instead of calling car_accelerate and passing it the external info on the car, you can just do my_car.accelerate(). It’s a nice, clean, organized, object that contains what it needs.
Latest Answers