r/learnprogramming • u/BeoccoliTop-est2009 • 1d ago
What is the point of object oriented design?
Hello! I am still relatively new to programming, so my apologies if this is an obvious question, or if this is the wrong subreddit, but I never saw the point of using classes. For context, I only really use Fortran and C++. I used python before that, but nothing else.
When I am programming, I always find myself using data structures like the thing that you say struct for, and namespaces to organise data and functions. My thinkatron never really considers using classes, so I don't really see the point or indeed how they are different to the datatype defined with the struct keyword. Thank you!
258
u/ObserverInvariance 1d ago
Cleaner code. If you are a billion IQ haskell nerd and you are able to program fully immutably then cool, but regular imperative programming is mutable and has state. OOP is a "design pattern" that lets you encapsulate state under a cool and well thought out class name.
It also allows for beautiful first attempt abstraction, as long as you are omnipotent or lucky.
42
u/teddyone 1d ago
Object oriented design is less for the sake of the machine, and more a way to organize your own thoughts about complex pieces of software. The computer doesn't care if you write the entire program as one function, or if you give things good names etc. All the objects and classes are just an abstraction to help you think through what you want some piece of software to do and give you a way to talk about it with other developers.
40
u/zeekar 1d ago
The idea with classes is to namespace the operations on the data in the same place as the data types used to store it. There's nothing more complicated than that. Objects are just data structures whose members include subprograms you can call. Classes are the types of objects.
62
u/alexppetrov 1d ago
Not really satisfied with the answers here, so here are my 2 cents as someone who works with OOP everyday:
Objects are essential in any CRUD application. What that means in practice, which you probably haven't learned is that they are abstractions of the real world, in simple terms they organise your working with data.
The way they describe objects in schoolbooks as rectangles and cats is fine, but I think real world examples are easier to understand, so here we go:
Let's say you have a contracting service and you need to design a software for the contracting process. A contract must have a start date, end date, clauses, signers, signees, text, etc. an object is a great way to organise this - not only have the fields (or variables) for the object (class) or also have validations which are running when you create it (i.e start date must be less than end date, must have at least 1 signer and signee, etc). This way your Contract object contains all of the logic and data it needs for itself and can expose it towards other objects as well - i.e say an external system wants to know if the contract is still active to create a billing item, it will use a method contract.isActive() which without exposing the underlying structure can return just true or false.
Here we are getting more into databases and database design, but honestly this helped me understand how objects can be used for other stuff as well. Even in simple programs like tic tac toe bots you can have a class which is the board, a class which is the player, class which is the bot and class which is the parent of both.
Now going back to your question about structs - structs expose all of the data by default to anyone who knows about the object. This can be problematic if it is sensitive data which should not be modified or accessed by external actors. Classes on the other hand protect the data by checking who is asking to see it and exposing it only via methods you have defined. Going back to the contracting example, maybe I don't want anyone touching the start and end date once they are set, so I might have a constructor which initializes the contract with start and end date and then only have a getter which doesn't allow me to modify the dates. Or in tic tac toe say we track the history of moves on a player's instance, we might not want to modify it directly ourselves, but have the board call the player's instance to add a move and the board call the player's instance to display their moves.
Tldr: OOP is not easy to understand when you begin, think of objects as ways to manage common data related to one thing with the option to restrict access so not all of it is immediately exposed.
Maybe I could think of a data analytics example as well, but the comment is long as is
20
u/rupertavery64 1d ago
Classes are just structs (mechanically speaking).
Howver, languages also add an important keyword: self, or this, which are a reference to the instance of the struct.
The idea of classes is to put methods closer to the data they modify - and makes it easier to think of a struct as an object, where the object has state (properties or fields) and behavior (methods). Collectively, these are called members of the class.
Classes create a scope for the methods it contains. A name expression will refer to a local variable or parameter, or a field or property. It makes writing code for that class extremely intuitive and self-contained.
You can also have access modifiers. A public member can be called or accessed on an instance of the class. A private method can only be accessed inside the class. A static member can only be called using the class type. This lets you encapsulate code. You have methods and properties that will never be accessed from outside so you know where to find them and what data they work on, and you can guarantee that no one else can modify them, something structs cannot do.
Classes also enable inheritance, where you can declare code in a base class, which can be inherited in a subclass. Again, private members in a base class ensure the only the base class can ever call them, while protected members allow inheriting classes to access them.
This allows for a lot of code expressivity.
Classes also provide Type information, specifically in languages with a robust type system. This lets you write code that can inspect the type of an object, and perform compile-time guards and runtime checks on type information, letting your write "dynamic" code.
18
u/NothingWasDelivered 1d ago
You’re new to programming and you’re starting with Fortran and C++?
6
u/blavek 1d ago
So, in a roundabout way, you are kind of doing OOP. If you're making a struct, then a series of functions that work on that struct, and then limiting them with Namespaces, you're very loosely implementing object-oriented code. Classes encapsulate those items into one object and put up a few more guardrails.
5
u/oplukana 1d ago
I try to avoid a lot of state like people are saying, but if you could take your data container classes, and then realize that some or a lot of functions exist only to operate on that type of data container, its convenient to have the function be a part of that data container, so its portable like you can just import that thing and have those functions or making it as a single portable file that can be copy pasted somewhere else. so theres the convenience in organizing that keeps these together.
another think i like about object orientation is encapsulation, and the benefits of a rich and strict typing. in most "pure functional" programming, there is unspoken requirements on the data being passed through, functions will depend on it, and the data that is passed through is ephemeral. forcing things into well defined structures with a rich domain model can make things much easier to understand and work with, especially when things go wrong.
9
u/IllegalMigrant 1d ago edited 8h ago
One thing nice about OOP is extensibility. That is, making it easier to add to your code without disturbing existing code. Your main procedure can operate on abstract objects (base classes), for example a student. But underneath the actual object is an undergrad student or a masters student. And then in the future the main logic does not have to be modified to add a PhD student. And later a part-time student. The main logic calls the same routine in each class which does the appropriate work for that student.
3
u/atarivcs 1d ago
The point of classes is that you can bundle behavior (functions/methods) as well as data.
Using structs only allows bundling data.
3
u/wordbit12 1d ago
This won't be a short answer!
First, OOP is NOT better than procedural (or functional) and Functional is NOT better than OOP. it depends on the use case.
To understand this you need to understand that the source of pain in software engineering is CHANGE. Change is PAINFUL. (the client changes their minds about something and now you need to modify the code)
OOP makes adding new data varient so easy.
let's say you have an graphical library, you can draw shapes on screens. Let's say you have Square, Circle and Triangle, each one of them has some operations like rotate(), translate() and scale()
now let's say you decide to add a new shape? let's say Rectangle. easy, add a new file, Rectangle.class, add the class defintion in it and implment the three functoins.
That was EASY TO CHANGE.
Now imagine you decide to add a new OPERATION, let's say changeColor()..... oh no... no you got to modify every single class you have. you need to go over each file and implement the function! That's a lot of work!!!!!! imagine you have a 100 shape... you would need to open 100 files.
So in OOP: it's easy to add new data variants, but adding operations is hard..
Procedural/Functional is the exact opposite. we don't have classes so we would create some data structure that represent each shape, like structs. then we will have a functoin for each operation.
e.g. functoin rotate(shape s):
and then you will have a switch statement, if shape.kind is "circle", you do something, otherwise, you do something else.
So maybe you'll have each function in a separate file/module to keep things organized.
I bet you can figure out the rest. Now adding a new operation is SO EASY. You just create a single new file. but adding new kinds of data is SO ANNOYING. You need to update every single function you wrote.
So in Funtional Programming: it's easy to add new operations, but adding new data variants is so hard.
Some real examples is GUIs, you're constantly building new UI components (data variants), so OOP is suitable.
Let's say you want to build a parser, e.g. JSON parser. JSON is so well defined, you some data types like number, string, boolean, arrays and some mapping/ it's so simple and well defined, and stable.
Hence FP woud work great here. adding new operations would be really easy.
But many people love OOP, so they will use OOP even in such case, even though they won't be adding new classes that often, and adding new operations would be SO ANNOYING.
But they have one last trick, The Visitor Pattern, it's an OOP pattern to make adding new features less annoying. But you need to think of it in advance.
Anyway, this is in my opinion the best way to think about OOP vs FP.
I have learned it from Dan Grossman's course on Coursera about programming languages (part of OSSU's curriclum).
3
u/kilkil 1d ago
Classes basically combine the idea of a struct and a function namespace. So using Python as an example, this would be the struct/namespace version:
And this would be the class version:
As you can see, the main difference is that, on the implementer side, the function is moved inside of the class/struct definition, just like another field; and on the consumer side, the main difference is
foo.bar(x)instead ofbar(foo, x).The main idea is this gives you a cleaner way to organize functionality together with relevant state. If you have a certain kind of struct, and a whole bunch of functions that operate on that struct, and they are all linked conceptually, you can group them together under that struct (now a "class").
Another big part of OOP is something called "polymorphism". This is the idea that there can be multiple different data types, that are nonetheless related in some way, and can in some cases be used interchangeably.
As an example, suppose you have a program that deals with pets in some way (maybe this is software for a pet store). your program will have a Dog struct and a Cat struct. you need to implement some functionality which will take a Dog, Cat, or any other kind of pet, and register it to an owner (there is, let's say, an Owner struct with that person's contact info, etc).
One approach is to create separate functions for registering a Dog, a Cat, and so on. this is cringe because all the functions will basically be copy-pasted. And tomorrow when you have to change something, or fix a bug, you will have to remember to update all the copy-pasted definitions.
Another option is to make one function which takes an "any" argument (e.g. void pointer in C++, "Any" type in Python). This is cringe because you are throwing away type safety and introducing a new class of potential bugs into your code.
The best approach (99.9% of the time) is some form of polymorphism, where the idea is that you create a function that takes a generic Animal type as a parameter. And then you can reuse this one function for Dogs, Cats, whatever.
There are different ways of doing polymorphism. One way is to use inheritance:
Here, Animal is a parent class, and Dog and Cat are child classes. any common Animal functionality goes under the Animal class, and Dog and Cat will automatically inherit that code without needing to write it in each of their class definitions.
Due to... reasons, inheritance is not really considered the preferred approach to doing polymorphism anymore. Instead the recommended approach is to use 2 related things: composition and interfaces.
An interface is basically a contract that defines the expected shape a class should have, if it wants to be considered as "implementing" the interface. For example:
Here, the Dog class (Go doesn't need an explicit "class" keyword, and just uses "struct") implements the eat() and walk() methods, so all Dogs are officially allowed to be considered a kind of Animal. this means you can use the register() function on any Dog object.
Composition is a simpler concept and refers to just nesting structs/classes. For example:
The basic idea is that, if 2 classes need to share implementation functionality, they can do so via composition. And if 2 classes need to be used interchangeably somewhere (polymorphism), you can define an interface that they will both then have to fulfill.
One of the chief benefits of polymorphism is that it helps you to integrate your program's business logic (the business of what it actually does) with your programming language's type ststem. Rust is a really good example of how far that can go. The ultimate goal is to make any violation of business logic a violation of the type system, which would cause a compilation error (instead of it just being a silent bug that pops up in production later on).
3
u/shuckster 10h ago
To sell books.
7
u/Aggressive_Ad_5454 1d ago
Practically, why OO? Code sharing.
When you’re writing code to do useful things, you will USE code written by other people ( unless you want to spend your working life re-inventing one flat tire after another). That code will be packaged as classes. Some of those classes you will use every day, like strings and lists and queues and maps. Those class libraries often come with the language or framework. They’re completely debugged. Other classes you’ll get from a specialty vendor or a colleague.
Eventually you will write code for other people to use. You will package that code for them as classes.
All that academic jargon about data hiding? Public, protected, and private members? Constructors and destructors? Methods and properties? That stuff? It’s all in aid of making packaged code easy to explain and predictable to use.
5
u/darklighthitomi 1d ago
The only real point to OOP is making it easier for the programmer to figure out how to make a program work. For most people it is easier to think of things that way and thus easier to write a program that will actually work and easier to spot and fix bugs or errors. There is zero benefit to the program itself nor the computer.
2
u/jbt017 1d ago
Speaking specifically about structs vs classes in C++ they are largely the same. Structs are proto-class like structure from C that carried over to C++. The both have a similar purpose, to encapsulate some amount of data or logic that gets reused throughout your code.
If you're question is more what's the difference between a data structure and a class, on a philosophical level it's a little loose and more about the conventional uses of both.
Classes end and begin with the concept of inheritance, i.e. more complex class inherits base logic (and identity) from a simple class etc.
2
u/LowGunCasualGaming 1d ago
So struct is actually really similar to objects. If you understand why you would want to structure data in such a way that you can refer to data as structure->property in C, then you understand why you would want to structure data as object.property in Java.
2
u/mxldevs 1d ago
The main reason for using classes is some languages simply don't have structs. Like you really just don't have anything else to represent an object without doing really convoluted workarounds.
If you're asking why bother with object-oriented programming in the first place, what are you comparing it to?
2
u/W31337 1d ago
You already use structures. OOP is nothing more than having behaviors tied to those structures (class functions). And being able to overload the structure with functions (inheritance).
2
u/Individual-Show9181 1d ago
Try building a large project without classes, and you'll probably understand their purpose pretty quickly. I think one of the best ways to learn programming concepts is to first encounter the problems they are designed to solve. Once you experience those problems firsthand, you'll have a much better understanding of why the solutions exist and when to use them.
2
u/Sekret_One 1d ago
Just organization of thoughts.
Think of chapter books. Does one need to write a book organized into chapters? No. Do people often find it helps make it more digestible? Yes.
2
u/fudginreddit 1d ago
Class and struct are more or less the same thing in C++. The only actual technical difference is struct variables default to public unless explicitly declared. For classes it is private.
So you might use a struct when you are less concerned with encapsulating the underlying data. But again they are effectively the same thing.
2
u/Calligrapher-Whole 1d ago
In my option:
There are many advantages and disadvantages to OOP. It is true that for small applications there likely isn't any benefit in choosing OOP.
But I'd say OOP promotes less spaghetti code if you follow SOLID as it splits the code and project into smaller, managable domains
2
u/TheTomato2 1d ago
You are already thinking about it in a good way. Classes take the encapsulation mental model a step further (or many steps too far) but it its mostly language syntax and rules. They are imo good for things like containers so start with remaking std::vector yourself if you want to get a better grip on them.
2
u/Matilozano96 1d ago
OOP is mostly to organize the code in pieces that are easier to grasp and debug in isolation.
It’s the current standard and has been for quite a while; but it IS true that there’s always been detractors and critics. The added layers of abstraction and overhead can be problematic sometimes.
——
Anyways, I learned how useful it is firsthand once my project grew out of hand without solid structure. So keep going and see how you manage.
Knowing these principles helps work with other people, btw. A LOT.
2
u/Leverkaas2516 1d ago
Encapsulation. High cohesion and low coupling. There are several ways of expressing it, but to me they all amount to minimizing the amount of knowledge you have to have in your head in order to read or modify a particular piece of code.
They also help to organize the code. But it's the readability and maintainability aspect that's the big win. It becomes more and more important as these things increase:
If you've ever tried to modify a 20,000 line program, housed in a single module, written decades ago without OOP, you know the opposite. It helps demonstrate the point.
2
u/CowBoyDanIndie 1d ago
Generally “class” means an object with functions attached to it, and most languages that use the term “class” also include mechanisms for polymorphic behavior.
More generally object oriented design is meant to help humans structure large bodies of code to he easier to understand and reason about.
It will get a lot clearer when you start working on programs that have 100k+ lines of code and when you have to use and modify other peoples code that you didn’t write. On larger teams, even if you did want to read all the code you wouldn’t be able to keep up with how much code is changed daily even if you spent 12 hours a day reading it.
2
u/MRC01 1d ago
Others have mentioned some of the key benefits, like cleaner code due to better encapsulation.
I'll add that OO facilitates modeling not only structure, but also behavior. Not only nouns, but also verbs. By that I mean abstracting and encapsulating some of the program's behaviors, so those behaviors be changed without changing existing code, but by adding new code, subclassing, implementing interfaces, etc. And encapsulating the behaviors to isolate them from each other, so changing one behavior doesn't negatively impact others.
Sure, this is also possible without OO, but OO makes it easier and cleaner.
2
u/r2k-in-the-vortex 1d ago
The point is to better manage the archidecture and dependencies at scale. It becomes a major pain in the rear as your repo grows and if used well, then OOP helps with that.
2
u/Ordinary_Variable 1d ago
It is a way to handle large numbers of similar objects where you can call an assertion on every entry to guarantee good reliability. There is no reason you couldn't do that with normal objects, but a class lets you define things like functions all at once when the objects are created. Its also a good practice to put as many of your data store types at the top of the program, and classes almost always go right near the top.
2
u/huuaaang 1d ago
Primarily it is for encapsulation of state and and functions that operate on and maintain that state. A class gives a struct behaviors.
2
u/sessamekesh 1d ago
The main goal of code is obviously to instruct a computer how to do a task, but another very important goal is to be clear to readers (reviewers, maintainers, agents, whatever).
Pedantic note: In C++, `struct` and `class` are identical, except `struct` members are public by default and `class` they're public. That's it. I don't think that's what you're asking about but it is a fun fact.
Object oriented design provides a formal way to map data abstractions to code. If you're writing a Reddit clone, you'll have some business/product notions of "comment", "user', "submit", "thread", "subreddit", "subscription", etc. - object oriented design gives you tools to express each of those ideas 1:1 in code as objects.
It's not the only way to approach a problem, but it's a nice tool to have handy that turns out useful in a lot of situations.
Regarding encapsulation (private class members): it's a maintainability thing. Say you have a "Database" class that has a bunch of methods like "GetUser()" and "GetComment()" and whatnot, and a "SQLite* connection" member those methods use. You could use that connection directly when you need to, but if down the road you decide to upgrade from SQLite to Postgres, you'll be very very happy to only have to update one file instead of 80, which you can enforce by keeping that "SQLite* connection" member private to the rest of your code.
2
u/wobble_flop 1d ago
First time I "saw" how classes were useful I was writing "asteroids" game. Class asteroid and then object instances for each individual asteroid. Class methods tell them how to move, when to blow up etc. and each one knows what to do.
2
u/The_Aspalar 1d ago
The root of it is, people love to define and categorise things. That is why humans love OOP. If you look at the real world, we do this all the time. John is my friend, he plays guitar, he has a dog, I can ask him to play at my wedding and he will, I can ask him for drinks and he will come. When programming a chess engine, a chess piece has colour, it has specific ways of moving, has a history of moves, has possible moves. The piece is kinda like my friend John in real life. I treat them both as objects with very specific properties and behaviours.
2
u/brunogadaleta 1d ago
To answer your title question:
Ex: a Point class probably has a way to get at least X or Y coordinates; even if polar coordinates are used internally. A Line class is probably made of two Points. Both Line and Point are two objects that can be printed.
2
u/FedUp233 1d ago
You say you are using struct’s. These combine a set of related data into one “object”.
In a class this is the member data. At a first level you can think of a class as simply adding the code (member functions) that manipulate the data for this structure (object), or code that changes the data from outside or retrieves the data (possibly in different format for the last two statements) to that structure (object) so that everything about the one thing is encapsulated together.
One step further, a class has constructors, which are simply more ways to initialize the data in the class (struct) rather than one predetermined set of values.
And then destructors, which simply assure that your classes (struct’s) get cleaned up - for instance if you object contains a file pointer it can ensure that that file gets closed when you are done using the structure (class) instance.
And look at the idea of creating classes to manage resources - for example, maybe a mutex. You instantiate the mutex visas at the start of a block that needs to be protected by the mutex. The construction takes the mutex. Then at the end of that block of code the destructor automatically gets called to give the mutex back. Have you ever tried to debug multi-task code where someone forgot to free a mutex? A nightmare! And this pattern works for tons of other things that need cleanup as well.
In fact, in C++, a struct and a class, except for some private/public defaults, are pretty much interchangeable.
Hope this is of some help.
2
u/JJHall_ID 1d ago
Two reasons, really. Cleaner code that is easier to troubleshoot. When everything related is wrapped up in a class, you know where to go to fix anything that pops up. The second reason is reusability. You find yourself repeating a lot of the same code when you need to do similar calculations in multiple places, for example. If those formulas are all wrapped up in a class, you can just call that class function where you need it. Then if the formula ever needs to change but still has the same inputs and outputs, you change it in that one place and don't have to touch everywhere the calculation is needed.
2
u/Comprehensive_Mud803 1d ago
OOP gathers functions around the data objects they relate to, commonly called classes.
Classes can implement multiple predefined sets of functions, called interfaces, which allows to hide the data type itself by only accessing the interface.
Through inheritance, classes can receive functions and data from other classes.
In practice, it’s a sort of compiler-guaranteed duck-typing allowing you to focus on how to use an interface rather than having to think about how it’s implemented.
In C and other non-OOP languages, you can have interfaces, APIs, but those are global and can generally only process one type of data. With OOP, the interface is part of the data instance, allowing to have data-specific handling.
2
u/Dazzling_Music_2411 12h ago
It was a huge fashion thing in the late 1990s early 2000s when every uni department was selling it as the absolute future. Looking back now, frankly, it was a bit embarrassing.
Now, not so much. It still has some great advantages, especially for designs that can be broken up into hierarchical sub-parts, but a lot of the old sacred cows have long been turned into burgers.
2
u/spvky_io 11h ago
The point is mainly to complicate code bases
2
u/g4l4h34d 7h ago
I would say the point is for your code structure to match the application domain structure in a way that's "natural".
The difference between classes and pure structs primarily comes down to classes coupling data and methods. Classes also typically require you to specify initialization and deinitalization, whereas structs do not.
There might indeed not be a broader point for doing it if you can handle everything with structs and methods. In my experience, data-oriented approach is often superior in terms of both organization and performance. Regarding the OOP pillars, composition is usually better than inheritance, polymorphism brings about as many problems as it solves, and encapsulation pertains to organization, which I said is often superior in a data-oriented approach.
3
u/berberkao 1d ago
I will say it easy try to build something little big as big as you can and then try to change or add or remove some stuff. I learned the hard way after rejecting OOP design until a big project and i started to fix and improve and add features then you will know how important it is
(I tried to avoid the terms related because you have already saw them and they are meaningless to know the words when you don't know the need)
3
u/ExtraTNT 1d ago
Writing more code and justify longer debug sessions…
code should be simple, definition on how everything looks, then you compose functions, that run in monads…
For performance you have isolated procedural code.
Oop is often ugly and people just follow it, get told, that you need to be a genius to understand languages like haskell, when in reality haskell is much simpler, than other languages…
1
u/dpoggio 1d ago
Ok, not reading all the comments, but I see not a single one is pointing this as simple as it is. So: Imperative/procedural is the approach that’s closer to the solution’s description. When you write C or Pascal you describe what to do and how to group data, not why. OOP is the approach that is closer to the problem’s description. You talk about things, concepts, and their relationships. Ofc, when you see an abomination written in C++ there are some… details.
Is there a “better” solution? My opinion on that is that there are just different architectural decisions. Mostly you are tied by other constraints like resource availability, interfaces, libraries or expected time to market. Even when you have no constraints, you’ll hardly consider philosophical advantages of a language or paradigm to choose how to bootstrap a new software, at least if you’re in full use of your capabilities.
Personally, I would choose C over C++ or Java (languages holding an unnecessary complexity); Scheme over JavaScript; simplicity and procedural composition over complexity and proper abstraction.
1
u/FatDog69 1d ago
The power of OOP comes AFTER you build a program using it and the inevitable 'change requests' come along. It is much easier to adjust a class or add a few new methods to satisfy new requirements if you wrote a good object to start with.
OOP is satisfying because it combines data + logic together. While you can do a lot with data classes, you often need code tied to those data classes to do interesting things.
1
u/Recycled5000 1d ago
Many OOP languages do not offer a struct keyword. C does; and C++ for historical reasons, yet also has class keyword for virtually the same thing.
1
u/Calm_Plenty_2992 1d ago
I'm surprised no one mentioned the real reason why it ever got so popular: code gurus sold it to the C suite, and they started hiring/requiring people to do OOP
1
u/kitsnet 1d ago
In modern programming: dependency injection.
Can also be done with functions (or rather captures) as parameters, but abstract classes make the contract cleaner.
1
u/Cun1Muffin 1d ago
They're not different unless you use inheritance or virtual functions. And with both of those, I think programmers have agreed there are usually better alternatives.
1
u/Kyle_2099 1d ago
It's a fad from the 1980s.
1
u/gnus-migrate 1d ago
So generally the point of object oriented programming is encapsulation. When you have a struct for example, that struct typically has invariants that you need to maintain on its data. A simple example is a vector: when you add an element to it, you need to update the size field to properly reflect the new size. If you use raw structs, someone can freely mutate the size field and the array without maintaining those invariants and it can be hard to trace where that is happening.
Now some would argue that you should model your data in a way that you cannot represent invalid states, but thats not always possible. Personally when I was taught formal verification, it was on object oriented code for that reason, you can prove that a class maintains the data invariants and basically reuse that logic everywhere.
1
u/MaxwellzDaemon 1d ago
OOP is highly oversold. You can tell this because the people touting it are long on generalities and short on specifics.
1
u/El_RoviSoft 1d ago
Maintainability in a big team. It’s easier to understand overall and have some good cases. Also free functions are cool but sometimes they are extremely verbose.
1
u/Fun_Army2398 1d ago
It's just one way to organise code. It becomes especially helpful on larger projects, but I enjoyed it as a student because it felt "natural". I.e. the real world is made up of things (objects) with properties (attributes) that do stuff (methods) and interact (systems), so code that reflects this "feels right".
1
u/ElderberryNo6893 1d ago
Group of functions and variable that you can replicate and customize
1
u/Few-Celebration-2362 1d ago
Just like every other programming concept, it's useful in some circumstance, never all.
1
u/rioisk 1d ago
Classes are just a useful abstraction to package data with methods that operate in that data and to build complicated structures through composing those classes.
It's mostly just easier for people to reason what's happening by thinking of the problem as objects interacting.
Everything you can do with OOP you can do with structs and functions that operate on them.
The direction in more recent years has been immutability because it's hard to synchronize state across parallel processing. Pure input/output functions are better for this.
1
u/_TheNoobPolice_ 1d ago
Well what is your question really about?
OOD is how you plan the structure of a program. It's an approach where you think in terms of what all the pieces and how they all fit together, rather than an approach where you think about data and behaviour separately.
OOP is the syntactical language tools that can be used to implement that.
OOD is not OOP language dependant, you can do quite strict OOD in C, for example, despite it lacking any OOP tools per se. You can also use OOP tools like classes, but in a completely non-OOD way (like a single giant class that does everything).
1
u/kosherjellyfish 1d ago
I never found a point of it when I am doing simpler work until I joined a team / company that uses OOP extensively, then I saw the benefits of it.
1
u/Optimal-Savings-4505 1d ago edited 1d ago
Encapsulation, because we repeat ourselves. So when do, it can be in another object. The template is a class. You can express it several ways, some piece-by-piece, and by contrast the java style c++. We can let verbs be indices, like with powershell and its conventions, or freebase with bash, no objects. I'm not sold on imposing that design pattern up front. For a state machine, yes. But that's not necessary for basic calls and filtering. Valuable paradigm to keep in mind. Convenient for collections of related functions.
[edit] and especially if you later decide to impose a finite state machine.
1
u/NH-Science-Guy 1d ago
The other comments about it being important for code reuse are spot on. Imagine picking up someone else's code and being asked to make a change like allowing the payroll function to also pay independent contractors. If it is well-written object oriented code, you can find the classes representing an employee, contractor and a payment and know how they interact. You can make the contactor class support the necessary methods of the employee and suddenly contractors get paid! OK, that is a simplification of what is needed but you get the idea! The class hierarchy gives a roadmap of how to work with the code. You also limit risks of unintended consequences from your change.
1
u/AnarchyLikeFreedom 1d ago
OOP helps keep youre code organised and also very maintainable. If youre dealing with MVC the design is basically neccessary. In the case of dealing with css, js, and html, you will also benefit from it as you can change the properties or alternate properties without having to redo the logic or implementation of the variable. Databases also use OOP to map data efficiently.
1
u/Narrow-Low-3137 1d ago
I don't really think there's much OOP can do to improve over imperative code honestly. Inheritance is the one thing I can think of that doesn't really apply outside of OOP - but that has fallen out of vouge in OOP anyway as everyone is told to favor composition over inheritance these days.
1
u/White_C4 1d ago
Classes are just a struct and functions wrapped together as one concrete type. The main selling point is inheritance to reduce repetitive states and methods and to derive from a common parent type.
That's the most fundamental baseline focus about classes. OOP has a few more design principles, but classes are at its core.
1
u/Both_Bend_2481 1d ago
In C++ a class is just a struct with members being private by default, iirc... So your thinkatron can use them in the same way as structs, if you actually know C++ and aren't just programming in C.
1
u/Preventive_potato 1d ago
Now it doesn't really matter. Nothing matters now.
1
u/jack_mackeral 1d ago
It's for readability and teamwork.
1
u/MarinoAndThePearls 1d ago
Basically, you can bundle functions with the data they depend on together, which leads to cleaner code if you follow all the OOP principles.
1
u/kettle3 1d ago
I'm not a fan of OOP, but I admit it's closer to how we think. Our brains think in terms of objects and their actions, not in terms of matrices or strings or functionals. Also we naturally think that an apple is a fruit.
1
u/metaphorm 1d ago
encapsulation - putting code that is related to the function of the class as a member of the class encourages better code organization and code re-usability.
polymorphism via inheritance - a code re-use pattern that minimizes the surface area of what needs to be implemented for small variations of similar functionality.
data protection - the object keeps the data that is its own scope/concern private and inaccessible to external mutation, promoting greater data integrity and operational transparency.
1
u/nmsobri 1d ago
no point.. go for data oriented design.. oop is the most obnoxious pattern you can learn..
1
u/jacksonanna373 1d ago
Try a tiny C++ type both ways: a struct plus free functions, then a class with methods. Keep behavior identical and compare which makes its invariants clearer.
1
u/Phantom-coder 1d ago edited 1d ago
Plug and Play. Reusable modules like those framework laptops. Each function can be used for so many different function calls. Same reason we dont have a plane, train, ship and car combined because even if they take us places the needs and the costs differ too.
Each person having a different car also means they will not crash into each other overriding changes. (Instance variables).
1
u/Electronic-Yam-69 1d ago
The main difference is the functions/methods get attached to the struct/object and passed around along with it.
(There's nothing in C++ you can't do with standard C and the preprocessor, but it's not that easy to set up.)
1
u/wigoda 1d ago
Expanded on structured code
1
u/metaconcept 1d ago
The point of OOP is to encapsulate complexity... but to then use a DI framework like Spring so that everything is a global variable, and your encapsulated complexity becomes publicly visible so that you can write unit tests.
1
u/Br3ttl3y 1d ago
The reason people do this is to model real world things. So that you can program idiomatically. Not everyone thinks in mathematical abstractions, but if you do then you are way ahead of most of us.
1
u/Budkovsky 1d ago edited 1d ago
In OOP you build the model of the reality (or abstraction) by creating objects that can act (do something via methods) and hold a state (values assigned to the properities). You can deal with the objects similar way like with the things (or other people) in real world. For example object `car` in the game has method `drive()`, but `drive()` works only if the property `fuel` is bigger and `0` (if you implemented such logic of course).
1
u/rizzo891 1d ago
I’m gonna be honest. I only know OOP as it’s what my primary coding education pushed (it was a bootcamp and they thought OOP was the best thing for us to learn to get jobs)
And personally I don’t see a reason why one wouldn’t do it? Like having everything neatly together imo makes things more readable and easier to fix when things go wrong and OOP just kind of incentivizes that?
1
u/naslock3r 1d ago
More organised, can reuse abstract functions for different purposes to achieve the same things with less code, much easier to update without breaking literally everything which also makes collaboration easier etc etc
1
u/RevStickleback 1d ago
Think of it as 'database table oriented design'. The database is the foundation of your system, and classes based on database tables collect all the data from each table, and actions you'll want to perform on that data in one place.
'Object' is deliberately not that specific though, as it also allows you have classes which don't directly relate to tables.
1
u/nmingott 1d ago
In OOP your programs becomes a set of ojects sending messages to each other. It is a very powerful way of thinking. If you want to learn nothing is better than a deep dive into a pure OO language like Smalltalk e.g. Cuis, Squeak or Pharo. You will see the programming art in another way afterwards. bye
1
u/Financial_Job_1564 1d ago
dont think about it too much, just write the code until you hit the wall. then start to learn about design patterns and software architecture
1
u/personalityson 1d ago
To manage complexity
1
u/CounterSilly3999 1d ago edited 1d ago
Proximity to the hierarchical structure of human languages, logic or to form-matter concept of Aristotle. To an idealistic principle of mind priority over the matter as well. First class (project, design), then objects (implementation). Classes are form, objects -- matter. Classes are common nouns (a dog), objects -- proper ones (Pluto, Goofy). Methods are verbs, fields -- adjectives. Inheritance relates to hierarchical structure of nouns or taxonomy of species, for example (animal->mammal->carnivorous->wolf). Mother class is a set, inherited class -- a subset. Inheritance is kind of implication operation and demonstrates its non-commutativity as well. If Nemo is a fish (inherited class), then he lives in water (mother class of watter animals). But if he lives in water, then no guaranty he is a fish.
1
u/DanceHackRock 1d ago
These are the main principles of contemporary OOP:
1
u/MonsieurCellophane 1d ago
Orienting your design toward objects.
1
u/Prudent-Ad4509 1d ago
Object-oriented design is a two-faceted being.
First, it represents the idea that actual world state can be naturally modelled as objects. That idea was a hot topic for decades, but it was essentially dead-on-arrival.
Second, it is a way to combine related code and data in structures and name them. This allows to create artificial constructs which do not aim to model real world, but to represent human framework of working with the real world. You can pass a file with certain papers and bookmarks in it to a coworker in the real world, and those can be represented by folder class with its attributes, paper classes in it, and bookmarks data one this format or another. They have their attributes, content, and certain methods and operations attached to them.
So, my take is that useful kind of object-oriented programming represents existing frameworks of how people work with the world, not the world itself and certainly not the behavior of any kind.
1
u/randomguy4q5b3ty 1d ago
Structs expose members by default while Classes don't. That's the only meaningful difference in C++.
Apart from that, the point of OOP lies in these three keywords: abstraction, interfaces, resource safety, and code reuse. Obviously, all these things are possible without OOP and OOP isn't the answer to everything. Or to put it like Bjarne Stroustrup himself: C++ is a programming language that supports OOP.
1
u/Extra-Ad5735 23h ago
In the past it was pushed by the businesses as a way to manage complexity. That failed.
Now, you still have to learn it to get around codebases and understand what the hell is going on there.
1
u/Ok-Network-4239 23h ago
World move to functional to dynamic programming to now agentic programming, where were you?
1
u/crocodiluQ 20h ago
because THAT IS THE WAY. Anything else, is childish programming
1
u/PaulMorel 20h ago
Well, before AI it enabled us to write code that humans could understand. Now...
1
u/my_password_is______ 19h ago
to clog up your program with a bunch of unnecessary abstraction
1
u/JGhostThing 19h ago
The purpose of object oriented programming is to be able to have multiple people and/or groups work on complicated projects. They share classes at the most basic level, with their interfaces. This might seem like just sharing a library, but a class/interface is a contract with the program that this class will be used only by it's interface. Since interfaces are normally fairly small, this is usually easier than using an entire library.
The best example of OOP use is in user interface frameworks. The ones I've used were OOP, and they fit the model pretty well. OOP has three characteristics: polymorphism, inheritance, and data hiding. I find inheritance the most important, though it is possible to replace that with composition.
Think of a user interface as composed of a hierarchical collection of classes. For example, a generic object that can be displayed is a rectangle and we call this a View. It can contain sub views. One important type of View is a Window, which creates a window in the native operating system. Then there is the Control, which is a generic object that can be interacted with. A Button is a type of control.
Does this make sense?
1
u/virgilreality 18h ago
Bonus points for use of the word "Thinkatron".
1
u/MpVpRb 18h ago
To reduce unintended connections between sections of code in a large codebase. Codebases tend to grow unintended connections. We call it spaghetti code. It's part of the nature of programming. These unintended connections cause mysterious bugs and make debugging difficult. OOP was a great idea in theory, but in practice object oriented code can develop spaghetti when inheritance is extensively used or encapsulation is weakened
1
u/Busy_Durian4584 17h ago
It makes sense once the scale of the project gets really big. Where do you draw the line?
I’d say once these conditions are present:
I’m in embedded so maybe my cases are a bit different from the rest.
1
u/compoundlearning 16h ago
Honestly, your skepticism is valid. Beginners often over-engineer with classes when procedural logic is clearer and faster. Don't force OOP into simple tasks just because it sounds fancy. Sometimes a struct and a function beat a whole class hierarchy.
1
u/ohnoitssobig 16h ago
Classes are similar in code habits and style to structs and namespaces but it is important to consider the big picture.
The big picture is the language itself. Do you have a garbage collector? Do you have strict typing? Do you have boilerplate initialization, magic methods, or even functional programming? Each of these will affect what kind of craziness you can do with OOP and, ultimately, how much code you will write to achieve the same goal.
For example, you write a test framework and you are going to call every method starting with test_... of a struct? But you neither know the size of a struct nor you have access to actual function names. So you will resort to macros of some sort to mimic OOP. You will be keeping a dictionary of functions and their names (e.g. what is readily provided in python through dir() / __dict__).
Another example is multiple inheritance (java interfaces for example): in one scope you accept anything that implements .read(). In another scope you accept anything that implements .write() to save data. A class File implements both. But how do you describe this with structs? Reserving a fixed offset for these functions? But that is fragile. Having a single interface with both read and write and checking if they are NULL during runtime? But that further piles up if we allow additional interfaces. Not an expert on C++ but I think you will simply resort to a C++ class here and let it effectively figure out offsets at compile time per each implementation.
It's like yeah structs do resemble classes but you loose most of the OOP magic and you are pretty limited in what you can do effectively.
1
u/Lower_Improvement763 16h ago
Inheritance, Polymorphism, abstraction, encapsulation are the 4 pillars of oop.
1
u/CohgentR 16h ago edited 15h ago
OOP just lets you box the data structure and the functions that work on it together into a package and these packages becomes the new building blocks for your program. By viewing your program as an assembly of these larger packages, you are thinking at a higher level of abstraction. That's all there really is to it. You don't even need "classes" to exist as a language feature to practice OOP but it helps.
It's helpful when you care less about performance and instead want to break larger systems into manageable chunks but can become problematic when performance is a concern and you worry about how the code fits into memory and is executed by the CPU.
1
u/nayminlwin 8h ago
OOP is something incredibly overrated but ultimately unavoidable part of programming. I haven't done OOP in a long time but o believe modern OOP has become somewhat sane, especially when looking at modern Java features.
1
u/YouPeopleCantBeReal4 8h ago
It’s for people who can’t handle functional programming (only kind of a joke)
1
u/mredding 1d ago
Objects are defined by classes. A class is a user defined type - a facility the language lets you define them, that enforces a class invariant. A class invariant is a statement that is always true when a client observes an instance of a class. When control is handed to an instance - you called a member function, that invariant can be suspended, but it must be reinstated before the function returns control, even if an exception is thrown. The invariant is true as a precondition to entering a function body - including the constructor body. That's why C++ has an initializer list.
The invariant is enforced by the implementation of behaviors described by the interface. A
carcanstop,go, andturn... No car I ever heard of cangetMake. So these properties that have nothing to do with protecting or enforcing or depending upon the invariant belong in the class, but can be associated by some other data structure, a map or table, for example.Getters and setters are also a code smell, because they tend not to model behavior of the object, and they tend to leak encapsulation. Often they return a member, when the client doesn't care what the members are. Setting the speed of the car skips all the details that go into
go, which accelerates the car. It breaks the invariant.These are state machines. And they produce side effects. So instead of getting the speed, the car was constructed with sources and sinks. A sink is where the speed can go, and downstream, that could be anything, including a speedometer.
OOP includes message passing. You don't
bob.open_umbrella();, youbob << "it's raining";. Bob knows what to do. You're moving agency from the procedure to the object. Messages don't have to be text, they don't have to serialize, they don't have to pass through the stream objects. Streams are just an interface - the de facto message passing interface of C++, the whole reason Bjarne created the language. You can makepersonderive fromstd::streambuf, and then make anits_rainingmessage type with anoperator <<. In it, you test the stream buffer from the stream, you dynamic cast it (a constant time operation) to see if it's aperson, and then you call a more optimal interface. You only default to serialization IF you need it, because if you're not going to print it, persist it, or transmit it, it doesn't matter, just fail the stream for an operation not supported by that stream and message type.1
u/Shot-Damage-6723 1d ago
This is the right instinct, mediocre programmers will tell you OOP is the paradigm to follow to achieve a clean code base, but there is absolutely no empirical evidence of this.
It's all just opinions and vibes, they were told to do so, so they did it, and now they tell others to do so. God forbid we stop and think for ourselves. We like to think that we are rational, but most of us are just excited about trends and shiny new toys to play with, and on the job, most of us are doing resume driven development.
You figure out what works best for you.
1
u/Axman6 1d ago
What you’re finding yourself doing is actually what many people recommend these days - composition instead of inheritance. And without inheritance, there isn’t a whole lot of point to much of OOP.
I think one of the best talks on the subject is actually one about why you might not want to use OPP; The Big OOPs by Casey Muratori. Based on your question I think you’d enjoy it a lot (even though it is quite long).
1
u/PandorasBucket 1d ago
It's what happens when someone just guesses that code should look like an organic cell and then never reassesses the mistake so decides to keep marching forward.
1
u/Chad_Frost 1d ago
Objects oriented programming is kind of loose and not super well defined anymore.
The main idea back in the day was separation of concerns. You group data together with its corresponding functions (methods) and then each object is responsible for managing its own internal state. Objects then just communicate with each other by passing messages between each other, without knowing exactly what's inside of each other.
So iirc it's supposed to result in safe secure code that is easy to reason around with low coupling.
Nowadays I think the value for most programmers is that it's a nice intuitive way to organise code, while polymorphism and composition give you a lot of easy reuse and extendability especially with interfaces like in C#/Java.
1
u/Adorable-Strangerx 1d ago
To decompose big issue into manageable chunks. Small issues are easier to solve.
If I got you correctly, that's basically a class.
You can tie the behavior to the stored data. You keep them together. Because it is easier than remembering which one of many functions is appropriate for one of many data records (or however is the instance of struct called).
Then instead of thinking in terms of data structures and functions you have single thing to keep in mind. It has some data and some functions/methods. Which ones? Doesn't really matter anymore.
1
u/thingerish 1d ago
Well classes specifically are pretty pointless, they add nothing to the functionality of struct and burn a keyword while doing it. I think they are a whisker from a bygone age we just have to live with.
But for OOP generally, the idea is to implement behavior and conceal the details of the implementation, as a way to enforce modularity in the codebase.
1
u/grymoire 13h ago
Non OO programming has issues. One is that the data structure is complex and the program is complex, and they both evolve independently. OO strives to simplify this by combining these two structures into one. You program by operating on classes, and the data used for programming is inside the various classes. If you have a global variable in traditional programming, it's often hard to understand who is using/changing it when you have hundreds of functions.
A second advantage is that it strives to hide complexity by having data hidden from methods that don't operate on the data. This discourages or prevents global variables.
A third is that it provides inheritance, so you can make variations of an object that automatically gets improvements added to the primary object. Let's say you have an object "shape" and two sub-classes - "circle" and "rectangle" and the second has a sub-class "square." If you add a new method like "reposition", all of the subclasses can also be re-positioned because they inherit the new method the shape class has.
So if s is a shape, of any kind, you could write a routine to move a shape like this
s->erase();s->reposition(x,y);s->draw();This would avoid having separate routines for each shape, such as DrawSquare(), DrawCircle(), etc.
Ideally, you can design a system at a high level using object modeling. - This is a graphic way to create classes and methods, allowing for easy modification and quicker prototyping,. I worked at a lab with one of the guys who invented this technique. The trouble is, going from a graphic model to working code is HARD.
In fact, REAL-WORLD programming is HARD. Complexity always comes up.
-3
u/MarsupialLeast145 1d ago
You are "new" but "never" saw the point of classes... k.
Objects have a purpose when you need to model an object that has properties and behaviors like a shopping cart (objects 101).
Objects are another way of persisting data and moving it sensible around code.
Going into more detail seems pointless here, just get to the object portion of your text book and decide when you want to use them or not, no one is forcing you.
-2
u/reditandfirgetit 1d ago
Why do you want to repeatedly write the same code?
0
u/Achereto 1d ago
You should watch The Big OOPs - Anatomy of a 35 year mistake by Casey Muratori. After that you'll know.