Trying to explain OOP in my own words, utterly failing at it.
Posted by Solid_Character9459@reddit | learnprogramming | View on Reddit | 64 comments
Why is OOP such a crazy thing to try to define in your own words, with it making sense? Everything I have read makes it even more confusing. All I got out of it is that OOP is a way of using objects than breaking them down even more to create a more complex system.
Am I on the right track, or do I have an extra hour of deep diving into this?
ninhaomah@reddit
If you are to explain OOP to someone else, how would you do it ?
Solid_Character9459@reddit (OP)
I would say that OOP is a way of using an object to establish a set of rules with attributes. Such as a lamp it has a light bulb, a lamp shade, a switch, and other attributes. Its set function is to provide light.
ninhaomah@reddit
That's all ?
Then where do inheritance, encapsulation and so on and on comes from ?
Pls don't look at just an object.
Look from the top. Look at objects.
Solid_Character9459@reddit (OP)
Okay, let me try something with more options.
The objects will be Vehicles; they have height, weight, type of propulsion, brand type, color, etc.
the object "helicopter" is based on "vehicles", with rotor blades to fly.
the object "car" is based on "vehicles", with four tires to drive on the ground.
ninhaomah@reddit
Let's look at vehicles...
They are all "vehicles" objects ?
All can do same things and have same features ?
I thought a normal sedan and a SUV are different in engine , wheel etc...
I am a motor noob.
Solid_Character9459@reddit (OP)
Holy crap, that is really breaking it down.
If that is the case, vehicles and cars would still be a class. We would have to get the class "cars" and the object "Sedan".
object "sedan" would have four doors, front wheel drive, etc.
Object "SUV" would have four doors, All Wheel Drive, etc.
Object "car" would be an inheritance of "vehicles"
ninhaomah@reddit
There you go.
Vehicles are superclass or at the top.. like animals...
Cars are sub class ... Like mammals
SUVs are a subclass of cars... Like homo sapiens
Then a Toyota SUV in the garage is an instance of a SUV class... And you and I are instances of homo sapiens class.
Vehicles have engines... Animals breathe..
Cars have 4 wheels , I know there are cars with 3 wheels but assume cars = 4 wheels for example..mammals are warm blooded
SUV can trek/hike , other cars can't. Homo sapiens can use Nukes.
You are a woman/man with so and so height and weight.. I am another man/woman with so and so height and weight.
We are unique but we are homo sapiens which is a sub class of mammals , which is a sub class of animals.
Yanniessim@reddit
Whats the point of explaining OOP if at the end of the day it depends heavily on use case for real world scenarios?
musbur@reddit
Bicycles don't.
ninhaomah@reddit
Ok
dmazzoni@reddit
I think the most important thing to understand about OOP is that it's entirely for humans, not for computers.
Computers don't need OOP. There's no reason for OOP other than to make it easier for humans to work with code.
In my opinion, the most useful purpose of OOP is to let you establish rules, so that somebody working with your code can't accidentally use it wrong.
That's why it's so popular at large companies. Someone can design a class and give it a very simple public interface. They can then trust that junior engineers can safely call the public interface and it will work correctly.
Similarly, it can enable someone to extend an existing well-written class and customize its behavior while ensuring the core functionality still works.
Without OOP, it'd be much easier for lots of people all working on the same project to do something wrong or break something.
Sometimes the goal is to enforce rules for yourself! Even if you're the only one working on a program, OOP provides a way to organize it and help keep you from accidentally using your own code the wrong way.
mrphysh@reddit
Yes. In any field progress is climbing on the backs of those that went before you. Object programming a strategy for passing software from one team to another. The detail of this communication is created by the teams. This is arbitrary and usually a bit weird.
Weak-Doughnut5502@reddit
All you really need for this is a halfway decent module system, and there are non-OO languages with a module system.
Rust, for example, isn't really an OO language, but it has a module system.
The feature that's more integral to the definition of OO is the dynamic dispatch. OO objects carry around function pointers to their implementation.
This allows you to say
shapes.map(shape => shape.calculateArea())
, and each shape can call a different calculateArea function.Implementation inheritance like this is occasionally useful, but is often considered an easy way to make difficult to debug spaghetti. There's a reason people say "prefer composition to inheritance".
danshat@reddit
Honestly while the encapsulation thing is really good and it does help to see where things should go and what should be used in your code, while learning some OOP concepts and patterns in Java I struggled to understand how ObjectCreatorFactoryMaker.Builder.Developer.Consumer helps developers in any way. If anything these complex patterns only make things worse from the perspective of someone who never wrote this code. Keep it simple and stupid is how I would write my code, if I had any professional experience lmao
beingsubmitted@reddit
That would be bad OOP. I think you're onto something with the observation that bad OOP doesn't help developers.
I do think that some people are dogmatic about OOP, and that has all the problems of being dogmatic about anything in code.
kneeonball@reddit
You’re saying that OOP’s main benefit is basically encapsulation. It’s not inherently wrong, and it is a big benefit of OOP, but we had encapsulation before OOP too, but as a convention, not built into the language structure itself.
OOP has some more structured approaches and ways to handle certain concepts, but everything it does existed before EXCEPT polymorphism, so to me that’s really the main benefit of OOP.
Being able to treat multiple types of objects that are related to each other the same dynamically. You can depend on an interface and have the calling code not know anything about the implementation details.
This is what lets you code against a logging interface or data repository interface and most of the code will never know or care about how those things are implemented.
It makes testing easier, because we can swap out implementations there more easily. It lets you use one logging framework for local development and then another that implements the same interface in production. Swap out data stores easily, etc.
Weak-Doughnut5502@reddit
The other main approach to encapsulation you'll see are module systems.
Modules allow you to control which functions and types you export, which builds encapsulation into the language itself.
OO was invented in the early 60s in Simula. Module systems were invented in the late 60s.
Modula and Algol were early languages with module systems. You see them also in more modern languages like rust or Haskell.
pjc50@reddit
The one thing that is important for the computer execution is multiple dispatch (virtual methods). That is, the implementation which runs when you call a function is determined by what the type of the object on which it is called, at runtime.
This doesn't strictly require OOP, but it is required for things like the Liskov substitution principle.
Solid_Character9459@reddit (OP)
This is the first time I have seen someone say it is not for computers, and that actually was the clicking moment for me. I was so stuck trying to connect it to code that I was failing to understand it from a very simplistic point of view.
jamills102@reddit
90% of coding is about how to organize your code
dmazzoni@reddit
Yes!
The computer enforces the rules for you - so it’s not like it’s just words.
But the reason for it is to add structure and organization to the code, not to make it work at all.
mrphysh@reddit
Object programming is a strategy for sharing software. I have jumped into this and have found success. Just focus on your goal and conform to the weird set of rules that go with object programming.
mrphysh@reddit
Object programming is a strategy for sharing software.
mrphysh@reddit
Object programming is a strategy for sharing software.
CodeMonkeyWithCoffee@reddit
OOP is an attempt to make apples part of a tree or a steering wheel part of a car. Sounds good in theory, but most of the time the tree will start growing pears you can only put in a basket of fruits if you make them unidentifiable generic fruits and the car will sonehow explode.
It's simple in theory, in practice it tends to (in my experience) only make your codebase more complicated as you start a fight with increasingly nomsensical martial arts techniques to make it work at all.
Some people stake their life on it. Just like some people stake their life on pure functional. The reality as usual, is somewhere in the middle.
Abstraction is the only concept i can still reliably use without everything exploding. Polymorphism, encapsulation and inheritance tend to lead to a lot of pain.
KirkHawley@reddit
I wrote a lot of object-oriented C++ code back in the day. My fruits weren't unidentifiable, and things didn't explode any more than things usually do.
KirkHawley@reddit
As an OOP newbie a long long time ago, working on a large procedural code base written in C, the initial benefit of starting to write C++ code was organization - suddenly it was possible to know without much thought where you were going to find the code that related to a specific type of task. It was REALLY helpful. That alone sold me on OOP.
Yes, a similar architecture could have been created by putting related functions in their own files or modules... but for some reason, it often wasn't.
NecessaryIntrinsic@reddit
OOP is just a programming paradigm that abstracted similar concepts for reusability.
Gugalcrom123@reddit
OOP means to create your own data types with their own operations, in order to make it easier to work with your concepts.
Weak-Doughnut5502@reddit
Not really a great definition.
In C, you can define new structs and functions on those structs.
In haskell, you can define new algebraic data types and functions on them.
Neither language is usually considered OO
Gugalcrom123@reddit
Indeed. Something like C's GObject which uses syntax like
gtk_label_set_text(label, "Hello, World")
with an opaque struct label is OOP. Just with a clunky syntax.Weak-Doughnut5502@reddit
You can manually emulate OO in C, but you don't have to and most C code doesn't.
You can just have stand alone functions working on your user defined types.
Gugalcrom123@reddit
Similarly, you can write non-OO code in Java. Having a class keyword doesn't mean the code is OO.
Weak-Doughnut5502@reddit
Ish.
The closest you can really get is just only writing static methods and never calling a single thing in the standard library.
If you're using instance methods, the code might not be good or idiomatic, but it's definitionally OO.
Writing non-OO code in Java is significantly more painful than writing OO code in C.
frnzprf@reddit
My attempt:
"Objects are packets of data with a type (= class) identifier attached to it. A method is a function that takes such a data packet as it's first argument. If an object is of a class C with a superclass S, then you can also call methods of S on objects of C — that's called 'dispatch'. The compiled code of the method will pass the call on to implementation with the most specific subtype."
If you use classes, you don't have to write this dispatching code yourself and change it whenever you create a new subclass.
xoredxedxdivedx@reddit
It's a typically very bad way to write code unless the problem space explicitly benefits from modeling everything as objects (pretty rare, but still sometimes it happens).
ninjashaun@reddit
"Oop is a way of using objects", is a little better here not there, I think. You could say "using objects is a way of Oop" and still be kinda right.
I'd say, oop is a way of grouping similar data, methods/behaviors together, typically to do with a certain theme or idea. Thats my high level, one sentence thought of it.
To go further, the by product of this grouping is the class definition*, which acts as a blue print. With the blue print, you can build the object, or two or three. (Aka creating an instance, or instantiating).
This last bit, this is what makes it object orientated.. if you weren't grouping like behaviors, and used your blue prints, to created objects, then you wouldn't really be programming in an orientation around the use of objects, right?
The even deeper level of oop I think would be the objects created are self contained (aka encapsulated) because everything they need, data, state, methods etc are all grouped within the object itself**, for the oop principles, depends how tight it loose you are with that. And you can have multiple objects, from the same blue print, that have all the same behaviors available, but all have their own state.
I'm more a write the message and delete before sending kinda guy, but hope this one does help.
** I mean given public methods to use the object, values might be set, behaviors may be actioned with input
danielt1263@reddit
The way I describe it is that OOP is all about telling objects what happened rather than telling them what to do.
Zesher_@reddit
I used to tutor students, and I used the same example my professor used when I learned from him.
A class is a blueprint, and an object is what's constructed with that blueprint. In the physical world, let's say you want a chair. A chair can have multiple properties, like it can have 3 or 4 legs, different colors, different heights, but a chair is still a chair. In code, you define what a chair can be, it has legs, it has a color, it has a height, and it has requirements like someone can sit on it. In a restaurant, you may need lots of different chairs, some for the bar stools, some for the short tables, some for the tall tables etc. Well since you have a blueprint of what a chair should be, you can create as many copies of that chair as you want and can vary the parameters that you defined and it will still be a chair and you can put it in your restaurant.
So instead of classes and objects, you could refer to them as blueprints and objects created from them.
In languages like Java that are focused on OOP, everything is basically an object. So even if you're dealing with a single restaurant, you'll have a class to define what a restaurant can be and create an object that is the actual restaurant.
azkeel-smart@reddit
For me OOP is a way to describe and manipulate a representation of a real life obejcts in code.
rhrokib@reddit
OOP is a concept. Every language implements the concept in their way.
If you could describe the concept in your own way, you’ve understood it. Simple.
SaltAssault@reddit
It helped me a lot in the beginning to think of classes as blueprints for special objects. All I can say is, don't worry. You'll eventually digest all of it, and it's perfectly normal to find it super confusing early on.
SynapseNotFound@reddit
I was always told it was easier to understand
Lets say we have a.. customer class, for our business app (lets just say its a web shop)
Then just by defining its name, we know whenever we have a customer object, we have access to things like:
Customers name, age, email, address, etc
What else? Maybe a list of previous orders?
Then we can make a reference to the Orders class. Its more simple. It contains a date, maybe a total price, and reference to the customer object.
Of course the order also contains a list of products.
So now we also need a Product class.
And so the system expands.
Whenever a thing in your system needs to contain more data and you group it together, why not make an object specficially for that?
By their names and general human logic you can guess what a product object contains.
You dont need to use objects (classes) when programming, but it can make it easier for a programmer to maintain and read the code
You would rarely make a class just for 1 thing
And in more advanced systems you might have more complicated classes that have functions that take multiple other objects etc
I was taught to describe workflow irl, and whenever you would use the words to describe an object in that flow… maybe you should CONSIDER making it a class in your system. Like, describe a webshop flow, and you will see you probably end up using the words customer, order, product and a few more.
Opposite_Mall4685@reddit
OOP is simply about messaging. The core idea is that the caller does not need to know what happens with their message, they only need to know what message to send. Sounds complicated, but it really isn't.
For example: You, the user, want an ice cream from the ice cream machine. You press a button with a flavor icon on it (your message) and receive, hopefully, an ice cream. What you did not see was the process that happened inside the machine, as that is part of the machines responsibility.
Antsolog@reddit
OOP has become a nebulous term over time such that it can mean everything and nothing. I have to prefix what I think it is with “it’s just my opinion man” as opposed to saying this is the agreed on definition:
I believe that OOP boils down to the idea that solutions to problems can be modeled as “objects” which are a collection of methods and data those methods manipulate.
Going a step further - encapsulation in this specific form means that users of the objects only need to understand its interface (that is the methods it exposes) should not need to understand the underlying object. An example of this would be creating an instance of a class called HTTPServer and using it will cause it to start an http server without exposing you to the underlying sockets or network protocols to make it work - you don’t need to know all of the variables used by HTTPServer.
SharkSymphony@reddit
The trouble here, of course, is that you haven't defined object. But yes, OOP is an approach to programming that's concerned with defining, creating, and using objects.
It sounds like you're describing decomposition, which is common to many programming paradigms.
AnswerInHuman@reddit
OOP is a programming paradigm, meaning a way to write code. There’s also other paradigms such as imperative, functional, logic…
In the particular case of OOP, the principle is we can create relationships by grouping similar values and processes together. Since this paradigm is based on “objects” as the name suggests that’s where we group these values. Kind of a multidimensional approach vs a linear one.
It simplifies certain things of the syntax because imagine writing the variables in imperative vs OOP.
int trainSpeed = 0; vs Train.speed int carSpeed = 0; vs Car.speed
Class contractors also allow us to initialize values sometimes with just a line of code when declaring an object that otherwise would have taken 10-20 variables by themselves. And would be harder to keep track of.
Then things like encapsulation and inheritance allow ever more complex relationships between those values and objects.
Far-Dragonfly-8306@reddit
In Python, you create a new object by creating a class. A class is just a blueprint for an object. A class (and therefore its object) has attributes and methods. The class "Cat" might have attributes "name", "breed", and "age." The methods for the Cat object are just functions that you can call on it. So the object Cat might have a method "meow()." This method can only be accessed by a Cat object. That's pretty much the first 30 seconds of OOP
for1114@reddit
Yeah, I like Far-Dragonfly on this....
myCat = new Cat("male"); yourCat = new Cat("hermaphrodite");
Creating instances of cat. A "collar" is an object you can put on a cat. myCat.AddObject(new Collar("yellow"));
Because of the attributes of Cat, like the default prototype attributes, the collar goes where the cat goes.
Like I get on the bus and then the bus has me which leaves me free to write code on paper or phones.
Or twiddle my fingers which are some of my human default attributes.
It's like I have a file folder with papers in it (properties) and other file folders in it (technically in an array called Children, but could be functions).
There's only a few things. Programming isn't that hard at its core. It gets difficult with more stuff that you add on, especially if it's not your stuff and you don't know what it is.
I learned mostly with Flash to make games, so that's way different than OOP for business applications. It works well for shopping carts and bullets. Like in Asteroids, you press the fire button which calls the function that you write to new Bullet(50 degrees, 121 degrees, 50mph, x, y, z). Or my ship.x, ship.y, ship.z.
It doesn't make much sense in some programs. Sure, if there is a lot of database work, you create a Class object for the database table (we call this a model). And a model can have other models in it or a list of models in it, but most of the time you just have one folder with all your model classes in it.
It's much different in gaming where you are creating instances of buildings and putting things in them and blowing them up with tanks and creating 1,000 newspapers and putting them all over the city streets and having the wind and cars blow them around in different directions and getting stuck on electric scooters in the rain.
lurgi@reddit
At its simplest, I'd say that objects are a bundle of data and the functions that operate on that data. A language that supports objects is one that gives you a simple way to say "Here is what this 'thing' looks like and here are all the functions that you can use to create/change 'things'".
That's not quite enough to match the formal definition, but it gets you pretty close.
_-PastorOfMuppets-_@reddit
I find the most valuable thing you can do when teaching anything is to first describe something commonly known first, and use that description as a veneer to what you're trying to teach.
So OOP is all about making and describing "things" or "objects". Take a basketball for instance. It has a shape, and that shape could be described as round. It has a color, described as orange. It has some actions it can do. It can bounce.
You can apply these descriptors to other balls. Say a baseball. It also has a shape, and that also could be described as round. It has. Color, but it is white. It does not have the bounce action (we're simplifying here)
In that way, you could describe an object, called "ball". The ball has some fields in it that describe what it is or what its doing
Name: "basketball" Shape: "round" Color: "orange"
It also has some actions with steps that can be described.
Bounce() Throw() Drop()
You could potentially describe other balls this way, by filling out the fields or implementing the actions differently.
Notice no nitty gritty has been discussed. We haven't talked instantiation, destructors, inheritance etc. We just established the core idea of what OOP is trying to accomplish.
With that, you've created a jumping off point to teach details.
johanngr@reddit
It is crazy thing to try and define because people who are authorities on it do not agree on a definition for it. Naturally, it becomes hard to define since it does not have a definition. There are many definitions, but just one word and this makes it a crazy thing. Would be better if those who pushed for terms actually managed to define the terms.
I usually contrast "object-oriented" to "type-oriented" and "type-oriented" to "typeless-oriented". Most people are not aware "typeless" even exists, but Assembly is typeless. Or, as typeless as the CPU (CPU does have "types" often as it has specific instructions and circuits for floating point math, this is also a reason that forced "type" into high level languages originally). "Type" was added (as just mentioned) partly because CPU started to get dedicated type with floating point, and also to support signed/vs unsigned and different sizes. "Object" takes "type" further so that any data thing can have operations associated with it. It is a natural progression. With this definition, it is very sensible. But then people add lots of more definitions, such as "you should always use lookup table for method calls and never just a normal hardcoded jump to subroutine" and whatever else.
Mattholomeu@reddit
An object is an abstract structure. It can 1. Hold data. 2. Perform functions/operations
That's a really basic way of looking at it that i think works well enough. It's kind of like defining an algebraic structure. You have a field with 1. real numbers 2. a set of operations you may perform on those numbers.
MaytagTheDryer@reddit
Many books describe OO in terms of OO principles, like polymorphism. That doesn't help people develop a mental model of what OOP is. OO is just a way of programming that models the real world.
On my desk right now there's a stapler. It weighs about half a pound, and it's black. I use it to turn a bunch of individual papers into a packet of attached papers. In OO, this object would be an instance of a Stapler class, that class would have the properties weight and color, and it would have one function/method, staple. The staple function would take one parameter, a collection of Paper objects, execute some code to transform that collection, and return a Packet object.
esplonky@reddit
OOP has Objects, and Objects have Attributes.
This is all it took for me to understand.
spidermask@reddit
Explain with real world examples, it's much easier, forget the programming/coding side.
DirtAndGrass@reddit
It's better to tackle the concept parts better, use analogies, like a class is a house design/blueprint, an object is the realization/constructed house.
Triumphxd@reddit
There are books. It’s a set of principles and patterns to guide design. It’s not something to distill into a single paragraph or sentence. If you want to understand it try a book, I don’t have a great one to recommend but it’s definitely been asked here before if you do a search. It’s definitely not an hour long process to understand its much more and to be honest the efficacy is debated but if you use any object oriented programming language you are gonna be bludgeoned with it. But yeah your small description isn’t… far off or anything.
Solid_Character9459@reddit (OP)
I have read multiple posts on them, but I felt weird commenting on year-old posts. Even those discussions don't make sense to me at all. Is there a reason behind not being able to distill it into a single paragraph or sentence?
DTux5249@reddit
Because it's a very nebulous term that over the course of its history has been used to mean different things by different people. Like, people are still arguing over what this term means to this day, and they refuse to agree on a concrete definition.
Typically though, OOP is, unsurprisingly centered around the idea of "objects"; encapsulated bundles of data, and functions what can interact with a given instance of said data. Under an OOP framework, a program is simply various interactions between different component objects.
In a tamagachi, you have a 'pet', that gets fed 'food' that you buy from the 'store', and keep in your 'inventory' until needed. The 'pet' can have different 'states' that effect its behaviour - states like "hungry", "happy" or "dead". All of these are displayed to the user of the game by a 'game window', and specific information can be managed by a 'settings manager'. You get the gist.
RunicResult@reddit
Yea you got most of it. It's just a way to make custom types and encapsulate logic within them.
So like your language might have primitives like
str
,int
,float
,bool
, etc.Using those you can make, idk, a
User { name: str, health: int }
obj, and encapsulate methods on it likeuser.heal(n: int)
.You don't see it here, but it's basically doing
heal(self, n: int)
, whereself
is automatically being passed in.There’s also polymorphism, which just lets two separate objs work on the same implementation logic if they meet a certain contract.
Like an interface
Healable
having the methodheal(n: int)
.If you implement that for both objs, you can write logic that just requires the obj to have the healable trait.
partyHeal(party: list<T>) where T: Healable
, meaning any obj that implements healable. This means if you end up later creating a new feature later this logic will still work without anything modification if you create like a `Familiar` obj and implement the trait "Healable" for it.kschang@reddit
To put it simply, OOP is more of a "system" packaging data with its related functions.
An object "pet" would have birthdate, name, breed, color, father, mother, gender, medical notes, temperament notes, etc. That's just data.
An object "dog" based on "pet" would add on siblings (list), photo (BLOB), and maybe functions bark(), dotrick() and so on.
But you can also create object "cat" based on "pet", add color notes, color pattern, photo (BLOB), siblings (list), preferred toy, etc.
l00pee@reddit
I loved the old java.sun tutorial on teaching oop. It basically taught it by using bicycles.
You can have an object type bicycle.
That object can have several properties and methods, depending on the bike. For instance (get it, ha ha), you could have a black beach cruiser with no gears and a coaster brake.
Another instance could be a red 21 speed with hand brakes.
Both the same type of objects, very different instances.
I could ramble on, but this was the light bulb for me.
HashDefTrueFalse@reddit
My attempt: OOP is an approach to program design that involves modelling real world objects and/or concepts in code by defining state and associated behaviour that mutates it. Program functionality is realised when objects interact with each other to do something useful.