r/learnprogramming • • 7d 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!

232 Upvotes

349 comments sorted by

284

u/ObserverInvariance 7d 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.

141

u/on-standby 7d ago

Cool class names like SingleSignOnTokenExchangeAttributeModuleServiceImplementationServiceUtil.java

67

u/DiodeInc 7d ago

Cool class names like SingleSignOnTokenExchangeAttributeModuleServiceImplementationServiceUtilFactory.java

11

u/Billy_Twillig 7d ago

You and u/on-standby should hang out. You both just made me titter.

7

u/DiodeInc 7d ago

I'm 2 steps ahead, we already do

→ More replies (2)

10

u/phoenix1984 7d ago

I feel like the bloat of Java gives OOP a bad reputation.

→ More replies (15)

1

u/BeoccoliTop-est2009 7d ago

Thank you. So, a problem that can be solved with OOD can be solved in other ways, but it becomes complicated in large projects.

14

u/ExtraTNT 7d ago

Thx for calling me billion IQ… never try haskell, so you never see through my disguise and find out, that i’m actually doing haskell, because it’s simpler…

9

u/thussy-obliterator 7d ago

Yeah but the word monad scary. Unlike the word object, which is definitely a familiar concept to everyone, and isn't actually an incredibly vague term that in practice refers to a fairly complex tuple of a region of memory, a struct, a vtable, and a reference to a garbage collector indirection table.

→ More replies (2)

2

u/NCKBLZ 7d ago

Do you use Haskell for work? What do you do? Why Haskell and not something else?

I wanted to learn it but then never committed, also because I don't have any reason to use it except that it seems cool

4

u/ExtraTNT 7d ago

Haskell for private projects, but work is functional c#…

And why haskell: is cool, decent fast, compiler catches a ton and it’s fun…

4

u/farfaraway 7d ago

I didn't really get OO until I programmed in Ruby, where literally everything is an object. Being able to reason about instances of objects really clicked for me.

That being said, I don't think it is always applicable and I generally prefer a functional approach today. 

8

u/swisstraeng 7d ago

What sucks is that some schools pushed OO like it was the new shiny at the cost of functional programming courses/experience.

3

u/farfaraway 7d ago

Honestly, I think that's fine. Every junior worth his salt starts with some language and eventually learns others. Along the way you learn new concepts, new ways of doing things, and new ways of thinking about problems. I'm still a terrible programmer, after 25+ years, but I found ways of solving problems that fit my limited capacity. Functional works OK for me. Maybe others would prefer some other method. Not really for me to say. I try not to be opinionated on what others do. 

→ More replies (2)

4

u/Achereto 7d ago

Cleaner code.

OOP doesn't actually give you that. You're way better off to have procedures where the first argument is a pointer to to some struct data. functionally identical, but way easier to extend.

Often it's even worse, because the interesting and useful behaviour of a program is the interaction between the objects you would create in OOP, so you end up constantly fighting the encapsulation boundaries in your code.

Unless your Object is a 100% self-contained thing (like DateTime ), classed and objects are most likely the wrong abstraction for whatever you write.

26

u/MyNameIsHaines 7d ago

You can argue that

class Rect {
    float x, y
    float Area() { ... };
}

area = r.Area()

is cleaner and more concise then

struct Rect {
    float x, y
}

float RectArea(Rect* r) { ... }

area = RectArea(&r)

The first also makes is easy to figure out what methods are available for a given object just by looking at the class declaration.

3

u/maximumdownvote 7d ago

If only we weren't limited to that bullshit language construct. If only

→ More replies (37)

7

u/BombasticCaveman 7d ago

This is such a lukewarm take, how does it get upvotes?

If you are working on any meaningful codebase with more than a handful of developers, please don't write code where you are passing pointers to structs.

EDIT: To extend this... raw pointers are just out of the question in any sufficiently large codebase. You can wrap them in protection, restricting what you can do to the pointer or who can access the pointer, but... uh oh you just introduced responsibility localized to a specific type of code. That's what we call a Class.

2

u/kpg_on_ao3 5d ago

> please don't write code where you are passing pointers to structs.

In every language, passing pointers to "structs" is the norm. You can't pass anything else for them. That's what pass by reference is, and whether it's Python, Java, Rust, C++, you're passing by reference anything that isn't a primitive.

→ More replies (1)
→ More replies (8)
→ More replies (10)

2

u/teerre 7d ago

That's a funny thing to say considering functional programming has way less concepts than OOP and achieves pretty much the same (if not better)

4

u/xpusostomos 7d ago

OOP and functional are orthoganal concepts. For example, the numeric tower in lisp, even when written purely functionally, is object oriented, because when you add different kinds of numbers together... Floating point, integers, complex numbers, a different routine or code needs to be called. Functional languages with no kind of object interface dispatch are kind of lame, which is why lisp dialects always port CLOS or similar.

→ More replies (5)

1

u/PressOnRegardless_IV 7d ago

> beautiful first attempt abstraction

<VB has entered the chat>

But yes, other than my.own.life.mistakes (as Integer) I really like this summary.

1

u/Fit-Replacement7245 7d ago

It’s also crucial not to confuse objects with OOP. Nearly all languages have data structures, methods, and references/pointers of some kind. OOP is unique because it allows inheritance and dynamic dispatch is the default over pattern matching. OP, look up programming languages courses on YT (MIT is free)

1

u/OkFox8124 6d ago

I'm mostly lucky.

1

u/kpg_on_ao3 5d ago

we're coming for your mutability, homeslice, prepare theyself

changing values, barf

1

u/mjmeyer23 5d ago

don't deny them the joy of refactoring. four or five abstractions later and you can still feel pretty clever.

1

u/thussy-obliterator 7d ago edited 7d ago

I find the tight binding between data types, runtime instances, and behavior often leads to messier code, not cleaner code. A procedural language with modules, parametric polymorphism, and interfaces (or traits or typeclasses or whatever your favorite term for type constraint bassd ad hoc polymorphism is) has none of the problems of OO and all the benefits. Unless you're gonna be the person to argue OO is when mailboxes and message passing, in which case yes OO is great.

→ More replies (3)
→ More replies (10)

44

u/teddyone 7d 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.

1

u/et_theextratestic1e 2d ago

This!

Now that we're heading into machines writing code for machines, they'll go back to functional programming. OOP comes with a high overhead.

42

u/zeekar 7d ago edited 3d ago

The idea with objects 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.

4

u/decrementsf 7d ago

Sounds classist.

3

u/kpg_on_ao3 5d ago

inheritance perpetuates a class-based society

2

u/mikekchar 7d ago

Even though I understand what you mean, I think there is something missing with this definition.

In OOP, there are 2 kinds of functions:

  • Ones that work directly with the underlying data in the data structure
  • Ones that do not work directly with the underlying data, but call functions that ultimately do.

You are intended to differentiate your code between the two and namespace accordingly. This is basically "encapsulation" (though I think that term is often used poorly).

The other important feature of OOP is polymorphism. This allows you to use the same function name for 2 different functions as long as the types of the parameters passed to it and/or the return type are different.

This means that area(rect) can be distinguished by the compiler/interpreter from area(circle). You can also write rect = create or circle = create if the compiler knows the types of rect and circle.

The idea is to allow generic functions that are of the second type of function that I listed. You don't have to write a different function for each combination of types that you are working with. Either the compiler does it for you, or it works it out at runtime.

This is OOP. Without encapsulation and polymorphism, you aren't doing OOP (though namespaces are still useful).

I should point out that I am describing "ad hoc polymorphism", but most OOP languages use "subtype polymorphism" where the function being run is only determined by the type of the "class" of the data structure. In the olden days that would typically have been the type of the first parameter passed.

Subtype polymorphism allows a limited form of polymorphism and thus enabled OOP for early static checked compiled languages. In those times ad hoc polymorphism was too memory and compute intensive to support in a statically checked language. However, the quirks that subtype polymorphism introduced turned out to be less than optimal in many situations. Usually you want to avoid inheretence (for reasons I won't get into).

I mention this because some people are confused when a language like Rust (which supports a limited form of ad hoc polymorphism) doesn't have inheretence. Many people can't understand how that can be an OOP language. But it has a more powerful form of polymorphism and it enables encapsulation.

→ More replies (6)

64

u/alexppetrov 7d 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

7

u/OurSeepyD 7d ago

Any case where you want have multiple self managing "things", I think OOP works nicely and serves as a really good mental model for the developer. Want to have n number of sockets? just instantiate them and configure them, and they "track" themselves.

A pandas table in Python is an object. It's nice to know that all its data is in there along with its functions (add data, remove data, count rows, etc).

I think the things that put people off OOP are:

  • examples they can't relate to
  • confusing words like "polymorphism"
  • very abstract and convoluted inheritance / interface relationships

4

u/soundoftwilight 7d ago

A critical thing for a new learner to understand as well is that OOP isn’t ever the only way to do anything. It’s definitely not the best way to do everything, either. But it’s the best/easiest/fastest way to do a lot of common things, to the point that it’s a good bet to default to OOP unless you have some reason to use a different paradigm. Like you mentioned CRUD apps that represent real world objects; most of the time that will be very easy to create in OOP and you won’t have to care at all about any of the downsides of OOP in that kind of app.

1

u/Karyo_Ten 6d ago

You can have objects without OOP. Rust, Ocaml, Ada work fine without OOP and have been used in industries with very high safety requirements (trading and aerospace).

In fact OOP with its inheritance and mutable state has a multithreading issue and mechanical sympathy / performance issue.

21

u/rupertavery64 7d 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.

2

u/metaphorm 7d ago

is a class just a struct? I think that varies by language runtime.

in language runtimes implemented in C, I guess that's basically true. what about languages that aren't implemented in C?

→ More replies (4)

20

u/NothingWasDelivered 7d ago

You’re new to programming and you’re starting with Fortran and C++?

11

u/Interesting-Agency-1 7d ago

Respect. Hardware aware programming has a steeper learning curve but once you understand it, it makes the rest of programming make so much more sense. Including OOP, and when to use it and when not to use it.

3

u/Every_Crab5616 7d ago

In my Apprenticeship we started in plain c for a year before going higher level

5

u/NothingWasDelivered 7d ago

Sure, but Fortran?

3

u/HawocX 7d ago

It's for attracting the opposite (or same, if that's you thing) sex.

2

u/Anabaena_azollae 7d ago

(Modern) Fortran is a great language and a very solid choice if OP is doing some kind of numerical computing.

→ More replies (2)
→ More replies (1)

8

u/wordbit12 7d 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/xpusostomos 7d ago

Talking about whether functional or object oriented is better is like asking if addition or multiplication is better. They are orthoganal, they solve completely different problems, they are complementary.

3

u/xoredxedxdivedx 7d ago

Even without OOP, when adding new “types” you don’t actually have more work to do with the switch statements, you have either the same amount of work to do or less.

You just tag whether it has a capability or not and then you have the same default/special split that you would get from virtual overrides, but you don’t have to buy into any of the other garbage. Everything OOP solves can be solved with data oriented design so you get all the pros and none of the cons.

2

u/wordbit12 7d ago

I don't understand your point. By switch statement, I meant dealing with each shape differently, since each shape can be rotated/translated with some different logic. It's just an example.
I don't understand how it's the same amount of work.
If you have each operation in a separate file, you'll be editing hundreds of files, and that's a pain. (There are, of course, ways to make change a bit easier, but I'm talking about the principles)
In OOP, you just create a single file, a class, and it has all the operations. It's much easier. I think it makes sense. It's not about the number of lines added.
This is my current understanding, do you think I'm missing something?

2

u/xoredxedxdivedx 6d ago

Yes, if you don't want things in 20 different files, you don't need them in 20 different files.

Switch statements and if else blocks can also encode for default behavior with "specialization" cases.

Also, operations should depend on behavior and data not a nominal type (especially not the ones that arise from OOP, which are completely orthogonal to what compresses code the most).

E.g., it's easy to tell that all shapes could probably share the same translate function, but once you go down the OOP rabbit hole, there are other operations that you would create separate implementations for because it's not always obvious that the underlying data is more homogenous, because it's completely obfuscated by splitting things into tons of objects with private members and accessor functions, you start to split your data and behaviors into complex webs that are untenable to understand, and this causes your codebase to bloat and complexity to start to increase exponentially instead of linearly.

Then things become more and more myopic, instead of simplifying entire systems, you get stuck bolting on new objects that interface with this complex web of disjointed other objects. The hidden coupling and state changes become extremely difficult to reason about, and you start to deal with unintended side effects, etc etc.

I mean to each their own, but after over a quarter century of programming with people in aerospace, game engines, quantitative finance, etc. While OOP was definitely shoehorned in due to the structure of educational systems over the past ~30 years, all of the very best programmers I've met tend to not like it very much, or openly despise it.

2

u/kpg_on_ao3 6d ago

I think what you're missing is the concept of sum types, which in the OOP approach can be thought of as a sealed class.

There's also type classes in the FP world, which you can think of as interfaces for the OOP world.

Rust uses "traits" and composition instead of inheritance

Python uses "protocols" and sum types

Haskell uses "data classes" and sum types

Unison uses "abilities" and sum types

etc

2

u/frnzprf 3d ago

I know about this problem of having to decide whether you want to be able to change data types or operations as "the Expression Problem".

It's called that way, because it comes up when you have an expression type for a programming language interpreter.

The visitor pattern is one attempt to solve it, but it's ugly. Multiple dispatch is another way to solve it with some other disadvantages.

Some OOP languages have a concept of both regular "open classes" and "closed classes". They both have advantages, but you have to choose one and try to predict how your program will change in the future to know which choice is better. You can't have your compiler complain when you miss a case of all variants of a data type in a case distinction when it's an open class, but you can have that when it's a closed class/interface/trait/typeclass.

It's also relevant if you want to extend some class from a compiled library with new variants. OOP lets you do that.

I don't know if that's what Alan Kay had in mind with Smalltalk, but to me OOP is about how the programming language facititates changes of the program in certain directions.

You need to manage changing programs when you have some big old software that a commercial client wants adjustments in but you also change from one program to the next during the development of any new prototype.

1

u/wordbit12 3d ago

Awesome, I didn't know it was called the expression problem. Thank you! I'll dig more into the matter.
It's amazing how pretty much everything about programming is all about trying to make things easier to change. It's beautiful and maybe even humbling. We're just trying to do the best we can in this ever-changing world.

1

u/ADHDick_in_ur_mouth 6d ago

Julia is the greatest implementation of functional programming I've seen. The hierarchical abstract type system with multiple dispatch makes it trivial to extend functionality to new data types. It is extremely elegant

1

u/artist-mode 2d ago

I disagree with some details of the examples:

  • Adding changeColor should in theory be easy with a well-designed class hierarchy; just add it to the base class and all the shapes inherit the method from it.
  • I feel that you’re conflating procedural and functional programming a bit here. Functional programming is fundamentally about treating functions as values, including an emphasis on using higher-order functions and anonymous functions (e.g. map, reduce, fold, lambda functions, etc.).

I agree that procedural, functional, and object-oriented all have their place. For procedural, I’d say that the main benefit is that the lack of abstractions compared to either object-oriented or functional programming give you a better overview of what’s done at the hardware level, which can be important for applications such as embedded systems or high-performance computing (in opposite ends of the computation scale).

1

u/wordbit12 2d ago
  1. You're right. but changeColor was just a small example; just imagine changing the shape's color needs some specific logic for every shape or something lol. That's not the main point.
  2. I consider FP and procedural synonymous. I never found it useful to make the distinction. I used to be more precise, but once I heard Dan Grossman, a man with a PhD in PL, literally say, "but people often confuse higher-order functions and first-class functions, so we won't care either". I started to not care that much about it.
→ More replies (1)

6

u/blavek 7d 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 7d 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.

1

u/xpusostomos 7d ago

I'm assuming by strong typing you mean static typing, which is completely different to strong typing. static typing has nothing to do with object oriented, it has nothing to do with pure functional. The most famous object systems in history were dynamically typed, CLOS and Smalltalk.

1

u/oplukana 7d ago

clos and smalltalk are not the most famous object systems in history, they are like cult classics. java and C++ are way more famous than they ever were.

you also seemed to completely miss my point in an attempt to do a "well actually".

→ More replies (2)

5

u/EedSpiny 6d ago

Preventing you calling .polish() on a dog or .feed() on a car.

6

u/Available-Skirt-5280 5d ago

You haven’t lived till you’ve polished a dog

3

u/CptBadAss2016 5d ago

Have you ever had your dog polished?

→ More replies (1)

4

u/Euphoric_Pop_1149 6d ago

lol i find this really hilariously true

2

u/VoraciousTrees 4d ago

What, you don't put mustard on your polish dog?

1

u/codeguru42 5d ago

I get the humor and I chuckled. On a serious note, you pass the dog or car as an argument in proceduaral or functional code. You will still get a type error if you pass the wrong argument. Under the hood . syntax is sugar for passing the first argument.

9

u/IllegalMigrant 7d ago edited 6d 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.

5

u/MercyHealMePls 7d ago

I disagree that "OOP is making it easier to add to your code without disturbing existing code", especially in your example of inheritance. While dynamic dispatch is great for polymorphism (and I think that's what you meant with your comment), inheritance also enforces incredibly tight coupling between base and inherited class, making it difficult to change or extend a written class, if your extension doesn't nearly fit your existing design. That's the whole goal of "composition over inheritance", to reduce that coupling and making extension and code change easier down the line.

3

u/Any-Ring6621 7d ago

Inheritance is probably the worst part of OOP, unless you’re developing from a precise spec and the code will never be changed after.

Taxonomic classification works well when your code is fixed and just needs to be written. As you say, once you get a feature request that doesn’t nearly fit in the box you thought you were creating, well, that’s when the shoehorning starts.

→ More replies (2)
→ More replies (6)

3

u/Interesting-Agency-1 7d ago

Yep, it's great for OLTP. Transaction oriented programming is fundamentally row-based, and so puting the encapsulation boundary around a single row, as opposed to each columns makes handling and processing tons of transactional records much easier and allows those systems to scale.

In that same vein, it's terrible for OLAP because most analysis is just querying individual columns of a table and all subsequent records in the table. If the query first has to find the column offset for each row, then that gets really expensive to scale. Indexes/hashmaps are cheap for lookups, but come with storage and maintenance costs, and so aren't ideal for raw analytical queries.

And this is all in the context of webdev, which is where transaction oriented programming really shines because all requests need to be packaged objects and sent over a network, and it's much easier to package and send a row along with it's corresponding logic in a nice neat bundle than to derive/aggregate and then package that all from each individual column in the record. This is less useful if your software runs locally only, which is why you see alot less OOP in desktop/local/native applications.

3

u/atarivcs 7d 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/kilkil 7d 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:

# foo.py
class Foo:
    prop1: int
    prop2: str

def my_func(foo: Foo, x: int):
    return foo.prop1 + x

# main.py
import foo

my_struct = foo.Foo()
my_struct.prop1 = 5
my_struct.prop2 = "hi"

n = foo.my_func(my_struct, 1)
print(n)

And this would be the class version:

# foo.py
class Foo:
    prop1: int
    prop2: str

    def my_func(self, x: int):
        return self.prop1 + x

# main.py
import foo

my_obj = foo.Foo()
my_obj.prop1 = 5
my_obj.prop2 = "hi"

n = my_obj.my_func(1)
print(n)

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 of bar(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:

// example from Java
class Animal {
    ...
}

class Dog extends Animal {
    ...
}

class Cat extends Animal {
    ...
}

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:

// example from Go
type Animal interface {
    eat()
    walk()
}

struct Dog {}

func (d *Dog) eat() {...}
func (d *Dog) walk() {...}

func register(animal Animal) {...}

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:

# Python example
class AnimalData:
    ...

class Dog:
    animal_data: AnimalData
    ...

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 6d ago

To sell books.

7

u/Aggressive_Ad_5454 7d 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.

4

u/thussy-obliterator 7d ago

Modules are a fine way to handle this without OO (common in FP and Procedural languages) and don't require code to be coupled strongly to a single data type.

4

u/Kyle_2099 7d ago

You can reuse code without OOP. Most people do.

5

u/darklighthitomi 7d 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 7d 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 7d 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 7d ago

I always find myself using data structures like the thing that you say struct for, and namespaces to organise data and functions.

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 7d 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 7d 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 7d 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 7d 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 7d ago

In my option:

  • It fits our usual understanding of world better (opinion based)
  • In large systems encapsulation and defining interfaces is very useful, it makes them easier to reason about
  • Inheritance allows for adding features or modifying behaviour without modifying the original class

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 7d 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 7d 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 7d 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:

  • Size of the code (10k to 100k to millions of lines)
  • Number of programmers
  • Programmer turnover
  • Age of the code

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 7d 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 7d 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 7d 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 7d 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 7d 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 7d 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 7d 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 7d 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 7d ago

To answer your title question:

  • Code reuse and behavior extension via inheritance.
  • Encapsulation to favor independence between an object apparent surface and it's implementation.
  • Reasoning via objects (data and methods that operate on it).

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 7d 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.

1

u/xpusostomos 7d ago

Another C++ centric comment that confuses the issue of what OO actually is.

→ More replies (2)

2

u/JJHall_ID 7d 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 7d 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.

1

u/xpusostomos 7d ago

Many OO languages are not compiled and calling a method doesn't guarantee anything. You are confusing the issues by talking about how some particular language you used does something, but it's nothing to do with what OO is.

2

u/Dazzling_Music_2411 6d 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 6d ago

The point is mainly to complicate code bases

2

u/YouPeopleCantBeReal4 6d ago

It’s for people who can’t handle functional programming (only kind of a joke)

2

u/g4l4h34d 6d 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.

2

u/iodine74 6d ago

I find it pretty interesting that you do C++ but don’t know OOP. My CS program was based around C and we learned functional (yes this was 30 years ago). A buddy of mine who went to a different university across the state did C++ in his CS program and he did learn OOP. And I’d always heard that was one of the main reasons for using that language.

5

u/ExtraTNT 7d 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…

2

u/oplukana 7d ago

hiding the dependencies and complexities into loose data is not actually simpler, it just looks simpler.

1

u/metaphorm 7d ago

OOP is a pragmatic compromise intended to make routine coding tasks more legible to average engineers who benefit from a coding paradigm that's a closer to match to their familiar thinking patterns.

it's not the most mathematically elegant or computationally efficient way of doing things. the purpose of OOP is for the engineering organization, primarily.

→ More replies (1)

3

u/berberkao 7d 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/readit_10 7d ago

bigger than an operating system?

3

u/Woshiwuja 7d ago

For most people is the other way around,, btw

0

u/[deleted] 7d ago

[deleted] — view deleted comment

1

u/berberkao 7d ago

I'm sorry i didn't understand your point

2

u/Shot-Damage-6723 7d 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.

2

u/Axman6 7d 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/dpoggio 7d 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 7d 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 7d 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 7d 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 7d 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 7d 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 7d ago

It's a fad from the 1980s.

1

u/gnus-migrate 7d 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 7d 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 7d 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 7d 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 7d ago

Group of functions and variable that you can replicate and customize

1

u/Few-Celebration-2362 7d ago

Just like every other programming concept, it's useful in some circumstance, never all.

1

u/rioisk 7d 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_ 7d 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 7d 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 7d ago edited 7d 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 7d 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 7d 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 7d 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 7d 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 7d 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 7d ago

Now it doesn't really matter. Nothing matters now.

1

u/jack_mackeral 7d ago

It's for readability and teamwork.

1

u/MarinoAndThePearls 7d 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 7d 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 7d 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 7d ago

no point.. go for data oriented design.. oop is the most obnoxious pattern you can learn..

1

u/jacksonanna373 7d 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 7d ago edited 7d 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 7d 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.)

→ More replies (3)

1

u/wigoda 7d ago

Expanded on structured code

1

u/metaconcept 7d 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 7d 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 7d ago edited 7d 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 7d 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 7d 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 7d 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 7d 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 7d 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 7d ago

To manage complexity

1

u/CounterSilly3999 7d ago edited 7d 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 7d ago

These are the main principles of contemporary OOP:

  • Encapsulation (what's in it is hidden/safe from outside access)
  • Abstraction + Polymorphism (the interface doesn't define the implementation)
  • Inversion of control (customizing behavior without touching the implementation)
  • (Inheritance is not as important as it was taught when OOP was new. Inversion of control took its place. Today inheritance is mostly used by interfaces.)

1

u/MonsieurCellophane 7d ago

Orienting your design toward objects.

1

u/Prudent-Ad4509 7d 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 7d ago edited 2d 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 four 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, but it's not an object-oriented programming language.

1

u/Extra-Ad5735 7d 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 7d ago

World move to functional to dynamic programming to now agentic programming, where were you?

1

u/crocodiluQ 7d ago

because THAT IS THE WAY. Anything else, is childish programming

1

u/PaulMorel 7d ago

Well, before AI it enabled us to write code that humans could understand. Now...

1

u/my_password_is______ 7d ago

to clog up your program with a bunch of unnecessary abstraction

1

u/JGhostThing 7d 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 7d ago

Bonus points for use of the word "Thinkatron".

1

u/MpVpRb 7d 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 7d 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:

  1. Multiple instances of a component that all have different states and configs
  2. Managing ownership and access to certain items (think a multicore system)
  3. You have multiple implementations that share the same interface. Ex: code base supports two different sets of HW

I’m in embedded so maybe my cases are a bit different from the rest.

1

u/compoundlearning 7d 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 7d 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 7d ago

Inheritance, Polymorphism, abstraction, encapsulation are the 4 pillars of oop.

1

u/CohgentR 7d ago edited 6d 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 6d 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/Ok_For_Free 5d ago

I separate the intent from the implementation.

I see the intent of OOP as a way to organize the logic of an application around an object. Or more abstractly, a noun.

From there, the question is how to organize the verbs. Encapsulation leads to a 'noun does verb' pattern, which puts the functions on the object. Polymorphism leads to 'verb acts on noun'' which leads to functions that operate on an object.

Your description fits more in the later because a function that operates on an expected data structure doesn't care about anything else. So object, class, struct, dictionary, map, record or any other key/value structure doesn't matter at the conceptual level. At the implementation level, you might need to pick a structure to take advantage of the language features and libraries.

1

u/nasanu 5d ago

I am so glad these types of discussions are only for the devs soon to be unemployed.

1

u/driad91 5d ago

The main point of Object Oriented Design is making your code as neat, readable, and maintainable as possible. If you look at a well designed object oriented code, it almost reads like a story. This makes it much easier to onboard people on your projects, which is essential if you're working at a large organization in a big team. It also makes it much easier for people to contribute to your code if it's open source.

1

u/Mango-Fuel 5d ago

OOP for me is about encapsulation, but I think generally it's considered that the point is actually polymorphism.

encapsulation means: you implement your "thing" in such a way that the internals are not accessible to the outside. just like your keyboard or monitor, there is a lot of internals but the outside world doesn't care most of the time about them. instead there is an interface provided to the outside world. the outside doesn't care how the interface works internally, only that you can see and make use of the outside interface.

1

u/Drummerx04 4d ago

The tldr for OOP:

You define both the data structure and the interface to that data structure with one type declaration and get a namespace for free. The definitions for init, destroy, and usage are all defined as a language construct and are thus harder to use incorrectly.

--------

My personal musings on languages/OOP:

C libraries very often use a bastardized OOP approach where you have a struct contain a context/instance of the library and then have init/destroy/usage functions which are needed to actually get it into and keep it in a valid state. It makes the lib much easier to use badly (even within the library implementation) and leads to UB, security vulnerabilities, etc. This appears to be the approach you currently favor.

I could get all into the OOP language structuring (polymorphism, inheritance, etc), but for me the real winning feature is just the ability to guarantee that a block of data (object) is programmatically valid to use at any given time.

Example: the humble std::string.

I don't have to worry about whether or not I can append to it, read from it, pass it to a function, assign it to another string, etc. If I have it I can use it safely and don't really need to worry about whether or not the person who passed it to me initialized it correctly or how I need to destroy it if I return early or whatever... Now, this is C++ so I can obviously still manage to do unsafe things with it, but the object itself is a valid piece of data.

Rust does a pretty solid job at fixing that particular C++ issue. Basically, it just doesn't let you do unsafe things until you figure out how to really hit the compiler over the head with a crowbar. Not a Rust dev btw, just acknowledging that the goal is important and that the language itself is a pretty solid risk mitigation strategy.

1

u/MauriceM7 4d ago

The reality is that you don't need it. But think of it like a clothes cupboard. Code organization in the form of Oop or any programming paradigm helps you to organism your cupboard. Shirts and pants on hangers, socks in drawers, shoes at the bottom. So when you need something it's easily accessible. Compared to just dumping you unironed clothes in a heap. You would still be able to find your clothes. It just looks neater organized.

1

u/CeccarelliPE 4d ago edited 4d ago

The world is a world of objects. I am a human. I have a house. My house has a table. My table has 4 legs. A human walks. A human talks. A human must be a male or female. A human object cannot exist unless it is either a male or female.

That is OOD. The point is that OOD models the real world. It describes the objects and how objects relate to other objects.

The language of C++ has the grammar elements that can describe the real world.

C does not. Fortran does not.

The closer a language comes to describing the real world, the more one can simulate the real world with that language.

1

u/whitenoize086 4d ago

For me personally object oriented programming reflects how people tend to think of systems. People tend to think of things in terms of what properties and abilities something contains and how that relates to a system. This allows an organized way of breaking down a problem and organizing it into sensible responsibilities. This is not the only way to model a system it just tends to be how humans best conceptualize systems.

1

u/sudden_aggression 3d ago

To reduce cognitive load when dealing with large complex systems.

OOP allows you to keep functions and variables confined to the areas of the system where they matter. They can be forgotten about when you're outside that part of the system. And it makes it easier to implement non-leaky abstraction, which also reduces cognitive load.

For example, code dealing with parsing telephone numbers only matters when you're dealing with the telephone contact info for a person. So you don't want to have to think about any of the details of that in 99 percent of the code that you write, even when you're dealing with a record of a customer that has contact information.

1

u/Skeptical_Giraffe 3d ago

Whenever you make a structure now, I'm sure you also make functions that take the structure as an argument and do things to it or with it. Instead, make it a class, and make those functions be members of the class. (And instead of taking it as a parameter, they operate on the current instance.)
Then you make the data members private, so the only way of using the class is through its member functions.
Here are some of the benefits:

  • Keeping every function focused on what its real job is, without mucking around in details it shouldn't have to care about. Technically you can do that with those structure-operating functions, but nobody ever does that consistently; it's too tempting to just use the structure members directly.
  • Enforcing things that need to happen when the data members are accessed or modified, like thread protection, logging, etc. You put it in one place, and now it just happens every time. No caller can break the rule or forget to do it.
  • When you need to change the internal data representation, you can do it in only one place, and the rest of your code doesn't change. It just keeps calling the member functions like before.

1

u/mredding 7d 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 car can stop, go, and turn... No car I ever heard of can getMake. 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();, you bob << "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 make person derive from std::streambuf, and then make an its_raining message type with an operator <<. In it, you test the stream buffer from the stream, you dynamic cast it (a constant time operation) to see if it's a person, 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/xpusostomos 7d ago

Another C++ centric comment that confuses the issue of what OO actually is.

→ More replies (6)

1

u/PandorasBucket 7d 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 7d 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 7d ago

What is the point of object oriented design?

To decompose big issue into manageable chunks. Small issues are easier to solve.

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.

If I got you correctly, that's basically a class.

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!

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.

3

u/xpusostomos 7d ago

Module systems decompose into managable chunks. Not really a good description of what OO gives you.

→ More replies (2)

1

u/thingerish 7d 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 6d 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.

-4

u/MarsupialLeast145 7d 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.

13

u/Justindr0107 7d ago

Interestingly aggressive on a learning subreddit. Tell me more about your father?

8

u/backfire10z 7d ago

> You are “new” but “never” saw the point of classes… k.

This sentence is completely useless to your reply unless your intention was to make OP feel bad. Was that your intent?

The rest of your comment is quite aggressive as well. Why bother replying?

2

u/firebush69 7d ago

There's that attention to detail: "moving it sensible"

Bro what and also please check your tone, this is a learning sub ffs

1

u/defectivetoaster1 7d ago

Write some C and you’ll realise you can go a long way with just structs and associated functions to model objects with properties and behaviours lol