eli5 what is object oriented programming? honestly eli5

1.52K views

eli5 what is object oriented programming? honestly eli5

In: Technology

9 Answers

Anonymous 0 Comments

It is a widely used strategy of programming where you represent, real life things as “objects” that “know things” and “do things”. So for example, if you made a video game, you may have a player object that “knows” it’s high score and can move across the screen (“do something”).

Anonymous 0 Comments

generic objects are defined by their fundamental parameters and then those objects are called upon in the program to engage their designed behavior.

i.e. a mouse cursor might be given the parameters for a black, outlined arrow (width=x, height=y, color=black, etc.) in the definition stage and then that object is called upon in the programming stage to visually track the *xy* position of the user’s interface (the physical mouse.)

Anonymous 0 Comments

A lot of what a program works with can be logically grouped as “objects”, or even just “things”. While keeping data stored in records with known fields (eg: a “person” may have a name, date of birth, etc) is nothing interesting, “object oriented programming” usually allows each type/category of object to do 2 major things:

1. Code can be written designed to be part of the object itself. This is often used to make sure the object is used properly and help minimize the risk of mistakes.

2. New object types can be created as a variant of an existing type. For example your “Person” type could be expanded into “Child” and “Adult”, or “Male” and “Female” variants, etc. They all still have names and dates of birth. But there are differences between them that the code should take care of when applicable, and in any case you can still treat them as each being a “Person” as usual.

Object oriented programming stresses the use of these styles and strategies of programming.

Want to add encrypted network communication? Take your “TCP_Connection” type and make a new version called “SSL_TCP_Connection”, then just use that any time you would use your original connection. If you did it right, it will just work and you can just pick which connection type you need when you create it and just roll with it from there.

Making a video game and adding a new monster type? Chances are it’ll be a variation of some generic monster, or a generic monster that can walk, or a generic monster with a weapon, or both.

Anonymous 0 Comments

Consider some things around you. Literally objects, like chairs, lamps, and pencils. Each has attributes, like weight, color, dimensions. Each has things your can do with them and possibly different ways of interacting with each other, or rules that protect them from misuse.

Object oriented programming is making computer data and process representation of these objects. You can have activities like “turn on” that make sense for lamps, but not chairs. Or maybe the is a chair where “turn on” makes sense, like a vibrating lounger. The size or color or uselessness of an object may be useful in parts of a program as the use of an object is attempted.

By making programs that understand these activities and different sets of attributes, we can create varieties of these data objects, and then treat them appropriately at the right time.

In real computing examples, you probably don’t have such diverse objects interacting. You’re probably going deal with them more abstractly. A store may sell chairs and lamps and pencils, but they don’t really turn them on our write with them. That’s information to share, not activity to perform. The dimensions and descriptions are more important.

In a game kind of programming, the myriad objects probably do get used more. A player might try to interact with an object. The lamp can inform that it can be turned on, the chair that it can be sat in, and the pencil that it can be used for writing or whatever. The things are a little “aware” of their capabilities, and can inform the uses when necessary.

Anonymous 0 Comments

Everyone’s giving you part of the answer–which is understandable, programming’s complex.

But I don’t see anyone addressing the contrast between object-oriented and procedural, which is key to understanding object-oriented.

“Procedural” programming is just a list of instructions. Do this, do that, do that, do that, do that. It can get messy, because you have variables all over the place and sometimes it can be hard because you don’t know how much stuff you’ll be working with.

So for example:

string student1Name = “John”
string student1LName = “Smith”
int student1Grade = 95;
string[] student1Classes = {“math”, “science”, “gym”}

string student2Name = “Jim”
string student2LName = “Jones”
int student2Grade = 85
string[] student2Classes = {“math”, “art”, “science”}

//Student 1 drops gym
student1Classes[2] = “”

//Student2’s grades improve
student2Grade = 95

See how that’s going? What about a class of 20 students? A college class of 300?

But what if you put all those variables into a nice little package that you can just tell to do stuff? That’s an object, and that’s the crucial difference between object-oriented programming and procedural programming: you’re both “encapsulating” the data so that only that which really needs to can see it, and also “abstracting” the processes of how to actually do stuff so that you’re not forced to repeatedly do stuff.

An object is a template that represents some logical structure that you can make many copies of, and each copy exists independently of the others. So going back to that example:

Student student1 = new Student();
student1.Name = “John”
student1.LName = “Smith”

Student student2 = new Student()
student2.Name = “Smith”
student2.LName = “Jones”

//Student 1 drops gym
student1.dropClass(“gym”)

//Student 2’s grades improve
student2.adjustGrade(95)

In that second example, it’s most of the same stuff–except that you no longer need to keep track of a thousand variables. All you need to know is student1 and student2, and those packages contain name, lname, grade, a list of classes, etc. You can tell it to do stuff (“dropClass”, “adjustGrade”) without having to worry about the manipulation of these internal variables required to accomplish that.

It greatly simplifies the process.

Anonymous 0 Comments

OO organises code into classes, properties, and methods. The simplest way to explain is with examples:.

Class: The definition of a Reddit account.

As part of my class, I need to define:

Properties: The information I need to store against a RedditAccount. I need a user name and an email address.

Methods: What I can do with a RedditAccount. I can create a post, reply to a post, or edit a post.

So what’s an object? It’s what I get when I actually use my class for something. Also referred to as an “instance”. AlterEdward is my RAccount object. It’s had all its properties populated, which means I can use its methods to make posts.

Anonymous 0 Comments

Right, so it’s all about reusability-

Basically, find repeating/ duplicate code and turn it into an object of the same class.

The alternative is to just write out brand new code as it comes up, without any concern for duplication.

From personal experience, writing one-off variables turns into a dumpster fire quickly.

Planning out what classes you’ll need does take more time, upfront.

But in the long run, much time is saved by having reusable functions / a pattern to build on.

It’s also about organizing code with the target object as the subject of action.
There is “object oriented css”, which tries to find generic html patterns, and then class names are based on styles, instead of targeting elements ad hoc.

For example, “.blue-picture-top-of-page” would be pretty specific, but imagine the same element instead uses classes:
“.blue-background .center-image” , or something like that….
One is extremely specific and has little reusability. But the other has a combination of generic classes, styled from the perspective of the element itself

Anonymous 0 Comments

To understand OO programming, you first have to understand procedural programming, because the former is built on the latter.

Procedural programming is like following a recipe (a procedure). Say you want to tell someone how to make bread. You can write a recipe by listing out the things needed to make it (these correspond to the data or variables in programming) and the steps you need to take (these correspond to the statements or functions in programming).

>**Bread**

>Ingredients:

>* Flour: 2 cups
>* Water: 1 cup
>* Salt: 1 tsp
>* Sugar: 1 tbsp
>* Yeast: 1 packet

>Stir sugar and yeast into warm water. Put flour and salt into medium mixing bowl. Slowly add the water to the flour, mixing as you add. Knead the dough for ten minutes. Let stand for 1 hour. Place on a pan dusted with flour and bake at 400℉ for 20 minutes.

Now, for object oriented programming, imagine a more complex recipe that takes several individual parts and puts them together, like a cake with icing. You could do this by making one big recipe, perhaps breaking it out into sections.

>**Cake**

>Ingredients:

>* Flour: 2 cups
>* Water: 2 cups
>* Eggs: 2
>* Butter: 8 oz.
>* Powdered Sugar: 1 cup

>Cake: melt 4 oz. butter. In a large bowl, mix melted butter, flour, 1 1/2 cups water, eggs, and 1/2 cup sugar until smooth. Pour into 8″ diameter round pan. Bake at 350℉ for 15 minutes.

>Icing: while cake is baking, melt the remaining 4 oz. of butter and mix with remaining 1/2 cup sugar and 1/2 cup water. Beat until creamy. Optionally, add food coloring.

>When cake is done and cooled, apply icing to outside of cake.

But there are downsides to that. The more complicated a recipe is, the more likely it is for you (or your readers) to get something wrong. Also, if you have two recipes that call for icing (say, cookies), now you have to write the icing section twice, once in each recipe.

So in object-oriented programming, you would break your parts out into separate full recipes, and just refer to them.

>**Cake**

>Ingredients:

>* Flour: 2 cups
>* Water: 1 1/2 cup
>* Eggs: 2
>* Butter: 4 oz.
>* Sugar: 1/2 cup
>* Icing (see p.2): 1 cup

>In a large bowl, mix melted butter, flour, water, eggs, and sugar until smooth. Pour into 8″ diameter round pan. Bake at 350℉ for 15 minutes. When done and cooled, apply icing to outside of cake.

>**Icing**

>Ingredients:

>* Water: 1/2 cup
>* Butter: 4 oz.
>* Powdered Sugar: 1/2 cup

>Mix melted butter, sugar, and water in a medium bowl. Beat until creamy. Optionally, add food coloring.

In object oriented programming, each recipe corresponds to something called a “class”, a self-contained piece of code that describes what an object is and how it’s made. An “object” or “instance” of a class corresponds to the dish that the recipe describes. When referring to an object in code, you don’t need to know how that object works or how it’s made. You only need to know what you can do with it, just like you can use either homemade or store-bought icing on a cake, and you can use icing on either cakes or cookies. This concept of objects taking care of themselves and not depending on other objects is called “encapsulation”, and while it’s especially important in object-oriented programming, it’s actually used in one form or another in nearly all types of programming.

PS.-I’m not a baker, these recipes are just for illustration. They’re probably very wrong.

Anonymous 0 Comments

Think of it like one of those huge toolboxes, the kind where every compartment has a mini-toolbox inside of it. Each mini-toolbox can contain both tools and more compartments.

Say you want to glue two pieces of wood together. First you are going to go to your *toolbox*. Within the toolbox, there a few compartments: carpentry, electrical, and plumbing. *Carpentry* is the relevant compartment, so you open it. Inside are some tools that are useful for pretty much any carpentry project: hammers, levels, clamps, etc. There are also some more compartments: nails, screws, adhesive. So you open the *adhesive* compartment. Inside are several types of glue: wood glue, super glue, hot glue, etc. So for you effort, you claim the *wood glue*. But before you can use it, you need to read the *instructions.* It says mix with 50% water. So you dilute the wood glue and complete your project successfully.

In this metaphor, the *big toolbox* is equivalent to a class. It is a container that holds other containers and tools. With a caveat. The top-level container does not physically contain the lower-level containers; rather, it lists their names. The “container” is literally a file (composed by the programmer as a text file originally).

The *compartments* (carpentry, electrical, plumbing, nails, screws, glue) are akin to classes as well. Relative to the toolbox, carpentry, electrical, and plumbing are *subclasses*, and the toolbox is their *superclass*. Likewise, nails, screws, and adhesive are subclasses of carpentry. They are the containers named by the top level container. They also name the container that contains them. (In other words, the superclass lists its subclasses, and the subclasses list the superclass they are part of). Again, these containers are files.

The tools (hammers, levels, clamps, wood glue, super glue, hot glue) are akin to methods. When a method hits the command line, it makes your computer perform an action, like drawing a line across the screen, closing an application, or altering a property within an application’s memory.

The instructions are akin to properties. They do not do anything by themselves. They are just values listed in the class. However, oftentimes, these values store information that guides how the methods perform. As previously mentioned, methods can also alter properties.

For example, imagine a video game with NPCs. The NPCs can become hostile to you if you wrong them, and they will remember your transgressions even if you leave and come back later. Therefore, you need to write a method that determines how the NPCs will react to you on sight. You call this method “onSight()” and you write it inside a class called “NPC”. “onSight” is triggered when an NPC sees you, and it contains two sub methods: “greet()” and “hostile()”. “greet()” makes the NPC greet you peacefully, and “hostile()” makes the NPC attack you. But how does “onSight()” choose between the two?

onSight() needs inputs to determine how it behaves. So inside your “NPC” class you also write a boolean property called “isHostile”. Now you rewrite “onSight()” to be “onSight(isHostile)”. Now when you call “onSight(isHostile)”, the game will check whether the NPC is hostile to help it determine what action to take. By default “isHostile” is set to 0, and “onSight(0)” will result in the “greet()” method running.

However, if the player does something to anger the NPC, you can write another method that runs whose effect is to change “isHostile” from 0 to 1. Now when “onSight(isHostile)” is called, it will be “onSight(1)”, and it will ultimately run the “hostile()” method, making the NPC attack you.

But wait, you might say. The class “NPC” is a file on my computer. Does that mean I have to make a class file for every individual NPC?

The answer is no, and this is where the “objected-oriented” part comes in.

In addition to properties, your code can contain variables, which are very similar to properties. Variables all have a type. Types are things like “int”, “string”, “bool” etc.

At the end of the day, these types are classes. And there is nothing stopping you from creating a variable of your own custom class. Thus, when you want to add a new NPC to your game, you don’t need to make a new file. You just need to make a variable of the class “NPC.” Such variables are called objects.

Objects can access all the methods and properties in their own class *and* in their subclasses. They cannot access methods and properties from their superclasses. So going back to the “NPC” example, the “NPC” class might be a subclass of “Game”. “Game” probably contains methods that do things like opening the main menu or saving the game. NPCs don’t need access to these methods, so it would be wasteful to declare an NPC as an object of the “Game” class. Everything an NPC needs to be an NPC is contained within the “NPC” class and its subclasses.

On the other hand, the “Game” class needs to be able to do things like create new NPCs on the fly to attack you, so “NPC” needs to be a subclass of game.

Going back to the toolbox example, say you want to start selling this toolbox in stores, and you fabricate it en masse. You might find that it’s being bought by carpenters, electricians, and plumbers, but they all have a complaint. They don’t need 2/3 of the tools in the toolbox–it’s wasting space and money. It would be more efficient to sell the carpentry, electrical, and plumbing mini-toolboxes separately.

On the other hand, a business that employs all three kinds of tradesmen might like to buy the full toolbox. Or someone thatching their roof might only be interested in the nails.

As a final comparison, these two things would be equivalent:

>Toolbox.Carpentry.Glue.woodGlue(instructions)
>
>Main.Game.NPC.onSight(isHostile)