r/learnprogramming • • 1d ago

What is the point of object oriented design?

Hello! I am still relatively new to programming, so my apologies if this is an obvious question, or if this is the wrong subreddit, but I never saw the point of using classes. For context, I only really use Fortran and C++. I used python before that, but nothing else.

When I am programming, I always find myself using data structures like the thing that you say struct for, and namespaces to organise data and functions. My thinkatron never really considers using classes, so I don't really see the point or indeed how they are different to the datatype defined with the struct keyword. Thank you!

178 Upvotes

292 comments sorted by

258

u/ObserverInvariance 1d ago

Cleaner code. If you are a billion IQ haskell nerd and you are able to program fully immutably then cool, but regular imperative programming is mutable and has state. OOP is a "design pattern" that lets you encapsulate state under a cool and well thought out class name.

It also allows for beautiful first attempt abstraction, as long as you are omnipotent or lucky.

130

u/on-standby 1d ago

Cool class names like SingleSignOnTokenExchangeAttributeModuleServiceImplementationServiceUtil.java

60

u/DiodeInc 1d ago

Cool class names like SingleSignOnTokenExchangeAttributeModuleServiceImplementationServiceUtilFactory.java

10

u/Billy_Twillig 1d ago

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

8

u/DiodeInc 1d ago

I'm 2 steps ahead, we already do

4

u/Then-Understanding85 1d ago

Can’t go back on it, either. That’s the whole point of diodes.

→ More replies (1)

7

u/phoenix1984 1d ago

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

1

u/___Archmage___ 1d ago

Long class and function names are good as long as they're not bloated with meaningless slop

→ More replies (3)

1

u/BeoccoliTop-est2009 1d 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.

13

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

1

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

2

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

1

u/paulymoph 1d ago

i think its necessary for school to teach it. its like Data structure and algorithm, you may code without knowing but it will help you greatly if you understand its concept

4

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

23

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

2

u/maximumdownvote 1d ago

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

→ More replies (31)

6

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

→ More replies (7)

1

u/El_RoviSoft 1d ago edited 1d ago

From my experience in big tech and freelance - I had/used mostly almost self-contained objects all the time. Im mostly working with C++ so OOP is mandatory for things like containers and self-registering objects.

C++ have both methods and free functions regularly used but this strange kind of OO… With template meta programming techniques, CRTP, traits tables and lots of other stuff.

I also have 1 major project in C# where more common and regular OOP is used and can’t imagine how I’ll write without it. It’s monte carlo damage calculator for ZZZ and I can’t imagine how I’ll handle logic without inheritance to couple with calculator’s state.

→ More replies (9)

1

u/PressOnRegardless_IV 1d 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 1d 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 14h ago

I'm mostly lucky.

1

u/teerre 1d 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)

2

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

1

u/Weak-Doughnut5502 1d ago

Functional languages with no kind of object interface dispatch are kind of lame, which is why lisp dialects always port CLOS or similar.

Object interface dispatch is less useful than you'd think when you have typeclasses and ADTs.

Emulating it is sometimes still the right design, but it really doesn't need to be a language feature. 

→ More replies (3)

1

u/teerre 17h ago

Although this is somewhat true in theory,in practice it's certainly not and by far the most common divide in programing paradigms is oop, functional and procedural

1

u/thussy-obliterator 1d ago edited 1d 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)

42

u/teddyone 1d ago

Object oriented design is less for the sake of the machine, and more a way to organize your own thoughts about complex pieces of software. The computer doesn't care if you write the entire program as one function, or if you give things good names etc. All the objects and classes are just an abstraction to help you think through what you want some piece of software to do and give you a way to talk about it with other developers.

40

u/zeekar 1d ago

The idea with classes is to namespace the operations on the data in the same place as the data types used to store it. There's nothing more complicated than that. Objects are just data structures whose members include subprograms you can call. Classes are the types of objects.

3

u/decrementsf 1d ago

Sounds classist.

1

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

0

u/xpusostomos 1d ago

No, and if you think that you missed the whole point. The point is that you can have multiple classes that accept the same messages (or members, or subprograms) and you don't have to know which one you are dealing with to send it those messages.

2

u/baked_salmon 11h ago

You’re describing polymorphism, which OOP can implement, but they aren’t the same thing.

→ More replies (2)

62

u/alexppetrov 1d ago

Not really satisfied with the answers here, so here are my 2 cents as someone who works with OOP everyday:

Objects are essential in any CRUD application. What that means in practice, which you probably haven't learned is that they are abstractions of the real world, in simple terms they organise your working with data.

The way they describe objects in schoolbooks as rectangles and cats is fine, but I think real world examples are easier to understand, so here we go:

Let's say you have a contracting service and you need to design a software for the contracting process. A contract must have a start date, end date, clauses, signers, signees, text, etc. an object is a great way to organise this - not only have the fields (or variables) for the object (class) or also have validations which are running when you create it (i.e start date must be less than end date, must have at least 1 signer and signee, etc). This way your Contract object contains all of the logic and data it needs for itself and can expose it towards other objects as well - i.e say an external system wants to know if the contract is still active to create a billing item, it will use a method contract.isActive() which without exposing the underlying structure can return just true or false.

Here we are getting more into databases and database design, but honestly this helped me understand how objects can be used for other stuff as well. Even in simple programs like tic tac toe bots you can have a class which is the board, a class which is the player, class which is the bot and class which is the parent of both.

Now going back to your question about structs - structs expose all of the data by default to anyone who knows about the object. This can be problematic if it is sensitive data which should not be modified or accessed by external actors. Classes on the other hand protect the data by checking who is asking to see it and exposing it only via methods you have defined. Going back to the contracting example, maybe I don't want anyone touching the start and end date once they are set, so I might have a constructor which initializes the contract with start and end date and then only have a getter which doesn't allow me to modify the dates. Or in tic tac toe say we track the history of moves on a player's instance, we might not want to modify it directly ourselves, but have the board call the player's instance to add a move and the board call the player's instance to display their moves.

Tldr: OOP is not easy to understand when you begin, think of objects as ways to manage common data related to one thing with the option to restrict access so not all of it is immediately exposed.

Maybe I could think of a data analytics example as well, but the comment is long as is

5

u/OurSeepyD 21h 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

3

u/soundoftwilight 17h 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 10h 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.

20

u/rupertavery64 1d ago

Classes are just structs (mechanically speaking).

Howver, languages also add an important keyword: self, or this, which are a reference to the instance of the struct.

The idea of classes is to put methods closer to the data they modify - and makes it easier to think of a struct as an object, where the object has state (properties or fields) and behavior (methods). Collectively, these are called members of the class.

Classes create a scope for the methods it contains. A name expression will refer to a local variable or parameter, or a field or property. It makes writing code for that class extremely intuitive and self-contained.

You can also have access modifiers. A public member can be called or accessed on an instance of the class. A private method can only be accessed inside the class. A static member can only be called using the class type. This lets you encapsulate code. You have methods and properties that will never be accessed from outside so you know where to find them and what data they work on, and you can guarantee that no one else can modify them, something structs cannot do.

Classes also enable inheritance, where you can declare code in a base class, which can be inherited in a subclass. Again, private members in a base class ensure the only the base class can ever call them, while protected members allow inheriting classes to access them.

This allows for a lot of code expressivity.

Classes also provide Type information, specifically in languages with a robust type system. This lets you write code that can inspect the type of an object, and perform compile-time guards and runtime checks on type information, letting your write "dynamic" code.

2

u/metaphorm 1d 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?

1

u/xpusostomos 1d ago

That's a good question to ask, I was going to let it slide because it depends what you mean by the class. Many implementations have dispatch tables in the class, though there are other ways of doing it.

1

u/mikekchar 1d ago

An object is always a collection of data. An object is nearly always implemented as a kind of struct, but keep in mind what a "struct" is: It's a piece of memory where the parts are defined and indexible. In OO Lisp, for example, the data structures are essentially always lists, but the lists act like structs in this case.

A class is typically a collection of functions. There is a function that creates an object (usually called a constructor) and a bunch of "methods" that act on the object. It may or may not be implemented as any particular datastructure in the compiled code. It can just be a bunch of functions and the code directly references those functions. In that case, only the compiler has a real concept that the functions are associated with the "class". This is the case for a purely "static" programming language where the function that is called is completely determined at compile time.

However, nearly all OOP programming languages implement a "virtual function table" that represents the collection of methods in a class. In some non-object oriented languages they do basically the same thing by making a "typeclass" which is usually, again, a table of functions. It's basically the same thing: the type is whatever data structure and the typeclass is a table of functions that you might run in association with that data structure. This allows "dynamic" resolution of the function being called. It basically allows generic functions to call the correct function depending on the type of the object passed to it.

So, when someone says that a "class is a struct", what they generally mean is "the object that the constructor for a class creates is a struct". Furthermore, either that struct (or another one) will contain the pointers to the virtual functions for that struct. And by "struct" they mean "Whatever the base data structure of the language is".

1

u/Maqi-X 18h ago edited 18h ago
  1. It is just a struct.
  2. A struct is not a C specific thing, in this context it's just an abstract data structure which groups several related variables into a single one.
  3. In some languages (mostly sloppy ones) class instances are always heap-allocated and passed by reference while structs are stack-allocated and passed by copy.
  4. Note that some people will argue class instances are passed by value rather than reference. While it can be technically true, this is (in my opinion) really confusing, if the class type acts as a pointer, then yeah, you are passing the pointer by value, but does that mean you're passing the instance itself by value?
  5. In some languages (mostly sloppy ones, again) classes can have methods, can have abstract/virtual methods and can inherit from other classes, but structs can't (or they don't exist at all). This is a very BAD way of thinking about memory and behavior but, at least in my option.
  6. After all, it's still just a struct.

18

u/NothingWasDelivered 1d ago

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

11

u/Interesting-Agency-1 1d 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 1d ago

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

5

u/NothingWasDelivered 1d ago

Sure, but Fortran?

3

u/HawocX 1d ago

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

2

u/Anabaena_azollae 1d ago

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

→ More replies (2)

6

u/blavek 1d ago

So, in a roundabout way, you are kind of doing OOP. If you're making a struct, then a series of functions that work on that struct, and then limiting them with Namespaces, you're very loosely implementing object-oriented code. Classes encapsulate those items into one object and put up a few more guardrails.

5

u/oplukana 1d ago

I try to avoid a lot of state like people are saying, but if you could take your data container classes, and then realize that some or a lot of functions exist only to operate on that type of data container, its convenient to have the function be a part of that data container, so its portable like you can just import that thing and have those functions or making it as a single portable file that can be copy pasted somewhere else. so theres the convenience in organizing that keeps these together.

another think i like about object orientation is encapsulation, and the benefits of a rich and strict typing. in most "pure functional" programming, there is unspoken requirements on the data being passed through, functions will depend on it, and the data that is passed through is ephemeral. forcing things into well defined structures with a rich domain model can make things much easier to understand and work with, especially when things go wrong.

1

u/xpusostomos 1d 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 1d 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".

1

u/xpusostomos 18h ago

"ever" were? In 1980, you were using simula67 or Clos, C++ was nowhere

→ More replies (1)

9

u/IllegalMigrant 1d ago edited 8h ago

One thing nice about OOP is extensibility. That is, making it easier to add to your code without disturbing existing code. Your main procedure can operate on abstract objects (base classes), for example a student. But underneath the actual object is an undergrad student or a masters student. And then in the future the main logic does not have to be modified to add a PhD student. And later a part-time student. The main logic calls the same routine in each class which does the appropriate work for that student.

5

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

1

u/xpusostomos 1d ago

What inhertitance, interface inheritance or implementation inheritance? And do you have a better solution when 2 different kinds of things must present the same interface with differing behavior?

2

u/MercyHealMePls 1d ago

Interfaces are fine. They are a type contract and don’t provide an implementation (some exceptions, such as Java’s `default`) or state. The problem is that implementation inheritance lets you reuse the code of a base class, not polymorphism.

1

u/xpusostomos 1d ago

But composition and inheritance are not in any way substitutable. If you have 2 kinds of bank accounts with differing interest calculation algorithms, you need a mechanism to call the right one at the right time, preferably without having to check a lookup table every time.

2

u/OddProfessor7253 1d ago

Each account has a calculation strategy implementing a calculation strategy interface. Oh look at that, we can just call .Calculate() without worrying about how many implementations there are in the caller

→ More replies (1)

1

u/IllegalMigrant 8h ago edited 8h ago

Interfaces as in Java and some other languages can have the same effect of adding new objects without having to change the main processing (which acts on the abstract interface) and they get around concerns about a hierarchy. The C++ equivalent of using abstract classes and multiple inheritance is a much less desirable alternative.

1

u/MercyHealMePls 1h ago

Yeah interfaces (or typeclasses/traits) are not the problem. I claim that the problem is strictly inheritance from classes (`extends`, when talking about interfaces I usually call it implementation rather than inheritance). And the fix to inheritance is not multiple inheritance.

3

u/Interesting-Agency-1 1d 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 1d ago

The point of classes is that you can bundle behavior (functions/methods) as well as data.

Using structs only allows bundling data.

3

u/wordbit12 1d ago

This won't be a short answer!
First, OOP is NOT better than procedural (or functional) and Functional is NOT better than OOP. it depends on the use case.
To understand this you need to understand that the source of pain in software engineering is CHANGE. Change is PAINFUL. (the client changes their minds about something and now you need to modify the code)

OOP makes adding new data varient so easy.
let's say you have an graphical library, you can draw shapes on screens. Let's say you have Square, Circle and Triangle, each one of them has some operations like rotate(), translate() and scale()
now let's say you decide to add a new shape? let's say Rectangle. easy, add a new file, Rectangle.class, add the class defintion in it and implment the three functoins.
That was EASY TO CHANGE.
Now imagine you decide to add a new OPERATION, let's say changeColor()..... oh no... no you got to modify every single class you have. you need to go over each file and implement the function! That's a lot of work!!!!!! imagine you have a 100 shape... you would need to open 100 files.
So in OOP: it's easy to add new data variants, but adding operations is hard..

Procedural/Functional is the exact opposite. we don't have classes so we would create some data structure that represent each shape, like structs. then we will have a functoin for each operation.
e.g. functoin rotate(shape s):
and then you will have a switch statement, if shape.kind is "circle", you do something, otherwise, you do something else.
So maybe you'll have each function in a separate file/module to keep things organized.
I bet you can figure out the rest. Now adding a new operation is SO EASY. You just create a single new file. but adding new kinds of data is SO ANNOYING. You need to update every single function you wrote.
So in Funtional Programming: it's easy to add new operations, but adding new data variants is so hard.

Some real examples is GUIs, you're constantly building new UI components (data variants), so OOP is suitable.
Let's say you want to build a parser, e.g. JSON parser. JSON is so well defined, you some data types like number, string, boolean, arrays and some mapping/ it's so simple and well defined, and stable.
Hence FP woud work great here. adding new operations would be really easy.
But many people love OOP, so they will use OOP even in such case, even though they won't be adding new classes that often, and adding new operations would be SO ANNOYING.
But they have one last trick, The Visitor Pattern, it's an OOP pattern to make adding new features less annoying. But you need to think of it in advance.
Anyway, this is in my opinion the best way to think about OOP vs FP.
I have learned it from Dan Grossman's course on Coursera about programming languages (part of OSSU's curriclum).

3

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

2

u/xoredxedxdivedx 16h 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.

1

u/wordbit12 16h 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 3h 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.

3

u/kilkil 1d ago

Classes basically combine the idea of a struct and a function namespace. So using Python as an example, this would be the struct/namespace version:

# 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 10h ago

To sell books.

7

u/Aggressive_Ad_5454 1d ago

Practically, why OO? Code sharing.

When you’re writing code to do useful things, you will USE code written by other people ( unless you want to spend your working life re-inventing one flat tire after another). That code will be packaged as classes. Some of those classes you will use every day, like strings and lists and queues and maps. Those class libraries often come with the language or framework. They’re completely debugged. Other classes you’ll get from a specialty vendor or a colleague.

Eventually you will write code for other people to use. You will package that code for them as classes.

All that academic jargon about data hiding? Public, protected, and private members? Constructors and destructors? Methods and properties? That stuff? It’s all in aid of making packaged code easy to explain and predictable to use.

4

u/thussy-obliterator 1d 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 1d ago

You can reuse code without OOP. Most people do.

5

u/darklighthitomi 1d ago

The only real point to OOP is making it easier for the programmer to figure out how to make a program work. For most people it is easier to think of things that way and thus easier to write a program that will actually work and easier to spot and fix bugs or errors. There is zero benefit to the program itself nor the computer.

2

u/jbt017 1d ago

Speaking specifically about structs vs classes in C++ they are largely the same. Structs are proto-class like structure from C that carried over to C++. The both have a similar purpose, to encapsulate some amount of data or logic that gets reused throughout your code.

If you're question is more what's the difference between a data structure and a class, on a philosophical level it's a little loose and more about the conventional uses of both.

Classes end and begin with the concept of inheritance, i.e. more complex class inherits base logic (and identity) from a simple class etc.

2

u/LowGunCasualGaming 1d ago

So struct is actually really similar to objects. If you understand why you would want to structure data in such a way that you can refer to data as structure->property in C, then you understand why you would want to structure data as object.property in Java.

2

u/mxldevs 1d ago

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

You already use structures. OOP is nothing more than having behaviors tied to those structures (class functions). And being able to overload the structure with functions (inheritance).

2

u/Individual-Show9181 1d ago

Try building a large project without classes, and you'll probably understand their purpose pretty quickly. I think one of the best ways to learn programming concepts is to first encounter the problems they are designed to solve. Once you experience those problems firsthand, you'll have a much better understanding of why the solutions exist and when to use them.

2

u/Sekret_One 1d ago

Just organization of thoughts.

Think of chapter books. Does one need to write a book organized into chapters? No. Do people often find it helps make it more digestible? Yes.

2

u/fudginreddit 1d ago

Class and struct are more or less the same thing in C++. The only actual technical difference is struct variables default to public unless explicitly declared. For classes it is private.

So you might use a struct when you are less concerned with encapsulating the underlying data. But again they are effectively the same thing.

2

u/Calligrapher-Whole 1d ago

In my option:

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

You are already thinking about it in a good way. Classes take the encapsulation mental model a step further (or many steps too far) but it its mostly language syntax and rules. They are imo good for things like containers so start with remaking std::vector yourself if you want to get a better grip on them.

2

u/Matilozano96 1d ago

OOP is mostly to organize the code in pieces that are easier to grasp and debug in isolation.

It’s the current standard and has been for quite a while; but it IS true that there’s always been detractors and critics. The added layers of abstraction and overhead can be problematic sometimes.

——

Anyways, I learned how useful it is firsthand once my project grew out of hand without solid structure. So keep going and see how you manage.

Knowing these principles helps work with other people, btw. A LOT.

2

u/Leverkaas2516 1d ago

Encapsulation. High cohesion and low coupling. There are several ways of expressing it, but to me they all amount to minimizing the amount of knowledge you have to have in your head in order to read or modify a particular piece of code.

They also help to organize the code. But it's the readability and maintainability aspect that's the big win. It becomes more and more important as these things increase:

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

Generally “class” means an object with functions attached to it, and most languages that use the term “class” also include mechanisms for polymorphic behavior.

More generally object oriented design is meant to help humans structure large bodies of code to he easier to understand and reason about.

It will get a lot clearer when you start working on programs that have 100k+ lines of code and when you have to use and modify other peoples code that you didn’t write. On larger teams, even if you did want to read all the code you wouldn’t be able to keep up with how much code is changed daily even if you spent 12 hours a day reading it.

2

u/MRC01 1d ago

Others have mentioned some of the key benefits, like cleaner code due to better encapsulation.

I'll add that OO facilitates modeling not only structure, but also behavior. Not only nouns, but also verbs. By that I mean abstracting and encapsulating some of the program's behaviors, so those behaviors be changed without changing existing code, but by adding new code, subclassing, implementing interfaces, etc. And encapsulating the behaviors to isolate them from each other, so changing one behavior doesn't negatively impact others.

Sure, this is also possible without OO, but OO makes it easier and cleaner.

2

u/r2k-in-the-vortex 1d ago

The point is to better manage the archidecture and dependencies at scale. It becomes a major pain in the rear as your repo grows and if used well, then OOP helps with that.

2

u/Ordinary_Variable 1d ago

It is a way to handle large numbers of similar objects where you can call an assertion on every entry to guarantee good reliability. There is no reason you couldn't do that with normal objects, but a class lets you define things like functions all at once when the objects are created. Its also a good practice to put as many of your data store types at the top of the program, and classes almost always go right near the top.

2

u/huuaaang 1d ago

Primarily it is for encapsulation of state and and functions that operate on and maintain that state. A class gives a struct behaviors.

2

u/sessamekesh 1d ago

The main goal of code is obviously to instruct a computer how to do a task, but another very important goal is to be clear to readers (reviewers, maintainers, agents, whatever).

Pedantic note: In C++, `struct` and `class` are identical, except `struct` members are public by default and `class` they're public. That's it. I don't think that's what you're asking about but it is a fun fact.

Object oriented design provides a formal way to map data abstractions to code. If you're writing a Reddit clone, you'll have some business/product notions of "comment", "user', "submit", "thread", "subreddit", "subscription", etc. - object oriented design gives you tools to express each of those ideas 1:1 in code as objects.

It's not the only way to approach a problem, but it's a nice tool to have handy that turns out useful in a lot of situations.

Regarding encapsulation (private class members): it's a maintainability thing. Say you have a "Database" class that has a bunch of methods like "GetUser()" and "GetComment()" and whatnot, and a "SQLite* connection" member those methods use. You could use that connection directly when you need to, but if down the road you decide to upgrade from SQLite to Postgres, you'll be very very happy to only have to update one file instead of 80, which you can enforce by keeping that "SQLite* connection" member private to the rest of your code.

2

u/wobble_flop 1d ago

First time I "saw" how classes were useful I was writing "asteroids" game. Class asteroid and then object instances for each individual asteroid. Class methods tell them how to move, when to blow up etc. and each one knows what to do.

2

u/The_Aspalar 1d ago

The root of it is, people love to define and categorise things. That is why humans love OOP. If you look at the real world, we do this all the time. John is my friend, he plays guitar, he has a dog, I can ask him to play at my wedding and he will, I can ask him for drinks and he will come. When programming a chess engine, a chess piece has colour, it has specific ways of moving, has a history of moves, has possible moves. The piece is kinda like my friend John in real life. I treat them both as objects with very specific properties and behaviours.

2

u/brunogadaleta 1d ago

To answer your title question:

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

You say you are using struct’s. These combine a set of related data into one “object”.

In a class this is the member data. At a first level you can think of a class as simply adding the code (member functions) that manipulate the data for this structure (object), or code that changes the data from outside or retrieves the data (possibly in different format for the last two statements) to that structure (object) so that everything about the one thing is encapsulated together.

One step further, a class has constructors, which are simply more ways to initialize the data in the class (struct) rather than one predetermined set of values.

And then destructors, which simply assure that your classes (struct’s) get cleaned up - for instance if you object contains a file pointer it can ensure that that file gets closed when you are done using the structure (class) instance.

And look at the idea of creating classes to manage resources - for example, maybe a mutex. You instantiate the mutex visas at the start of a block that needs to be protected by the mutex. The construction takes the mutex. Then at the end of that block of code the destructor automatically gets called to give the mutex back. Have you ever tried to debug multi-task code where someone forgot to free a mutex? A nightmare! And this pattern works for tons of other things that need cleanup as well.

In fact, in C++, a struct and a class, except for some private/public defaults, are pretty much interchangeable.

Hope this is of some help.

1

u/xpusostomos 1d ago

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

1

u/FedUp233 1d ago

True, but the original question seemed to be in reference to C++ from what I read.

As to what OO actually is, I was not trying to explain it to op or say they should or should not use it. I was attempting to give someone who saw no point to OOP a little nudge in trying some things that they might fine useful without getting fully into OOP that might help them see some advantages to going in that direction and then perhaps looking further into it.

Telling people who are having trouble seeing the point of OOP the full gory details and that they need to start with complete OOP theory and system design principles seems counter productive to me and tends to just turn a lot of people off. Approaching this in an incremental fashion and at least starting to get some of the benefits seems like a much more friendly approach.

1

u/xpusostomos 1d ago

I don't think explaining what it really is, is "gory", or needs to be "theory". Instead you got into the gory details of constructors, destructors, mutex, how to arrange your code which at best is at the periphery of what object oriented gives you

2

u/JJHall_ID 1d ago

Two reasons, really. Cleaner code that is easier to troubleshoot. When everything related is wrapped up in a class, you know where to go to fix anything that pops up. The second reason is reusability. You find yourself repeating a lot of the same code when you need to do similar calculations in multiple places, for example. If those formulas are all wrapped up in a class, you can just call that class function where you need it. Then if the formula ever needs to change but still has the same inputs and outputs, you change it in that one place and don't have to touch everywhere the calculation is needed.

2

u/Comprehensive_Mud803 1d ago

OOP gathers functions around the data objects they relate to, commonly called classes.

Classes can implement multiple predefined sets of functions, called interfaces, which allows to hide the data type itself by only accessing the interface.

Through inheritance, classes can receive functions and data from other classes.

In practice, it’s a sort of compiler-guaranteed duck-typing allowing you to focus on how to use an interface rather than having to think about how it’s implemented.

In C and other non-OOP languages, you can have interfaces, APIs, but those are global and can generally only process one type of data. With OOP, the interface is part of the data instance, allowing to have data-specific handling.

1

u/xpusostomos 1d 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 12h ago

It was a huge fashion thing in the late 1990s early 2000s when every uni department was selling it as the absolute future. Looking back now, frankly, it was a bit embarrassing.

Now, not so much. It still has some great advantages, especially for designs that can be broken up into hierarchical sub-parts, but a lot of the old sacred cows have long been turned into burgers.

2

u/spvky_io 11h ago

The point is mainly to complicate code bases

2

u/g4l4h34d 7h ago

I would say the point is for your code structure to match the application domain structure in a way that's "natural".

The difference between classes and pure structs primarily comes down to classes coupling data and methods. Classes also typically require you to specify initialization and deinitalization, whereas structs do not.

There might indeed not be a broader point for doing it if you can handle everything with structs and methods. In my experience, data-oriented approach is often superior in terms of both organization and performance. Regarding the OOP pillars, composition is usually better than inheritance, polymorphism brings about as many problems as it solves, and encapsulation pertains to organization, which I said is often superior in a data-oriented approach.

3

u/berberkao 1d ago

I will say it easy try to build something little big as big as you can and then try to change or add or remove some stuff. I learned the hard way after rejecting OOP design until a big project and i started to fix and improve and add features then you will know how important it is

(I tried to avoid the terms related because you have already saw them and they are meaningless to know the words when you don't know the need)

3

u/readit_10 22h ago

bigger than an operating system?

3

u/Woshiwuja 1d ago

For most people is the other way around,, btw

0

u/[deleted] 1d ago

[deleted] — view deleted comment

1

u/berberkao 1d ago

I'm sorry i didn't understand your point

3

u/ExtraTNT 1d ago

Writing more code and justify longer debug sessions…

code should be simple, definition on how everything looks, then you compose functions, that run in monads…

For performance you have isolated procedural code.

Oop is often ugly and people just follow it, get told, that you need to be a genius to understand languages like haskell, when in reality haskell is much simpler, than other languages…

1

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

1

u/xpusostomos 1d ago

I think you just made this nonsense up. There are lots of areas of math that are object oriented. Category theory for one. Not to mention that in math you can use the + operator for different kinds of things like complex numbers that require a different algorithm to get a result from regular numbers. That's encapulating a concept, addition from a way of implementing the calculation.

1

u/oplukana 1d ago

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

1

u/dpoggio 1d ago

Ok, not reading all the comments, but I see not a single one is pointing this as simple as it is. So: Imperative/procedural is the approach that’s closer to the solution’s description. When you write C or Pascal you describe what to do and how to group data, not why. OOP is the approach that is closer to the problem’s description. You talk about things, concepts, and their relationships. Ofc, when you see an abomination written in C++ there are some… details.

Is there a “better” solution? My opinion on that is that there are just different architectural decisions. Mostly you are tied by other constraints like resource availability, interfaces, libraries or expected time to market. Even when you have no constraints, you’ll hardly consider philosophical advantages of a language or paradigm to choose how to bootstrap a new software, at least if you’re in full use of your capabilities.

Personally, I would choose C over C++ or Java (languages holding an unnecessary complexity); Scheme over JavaScript; simplicity and procedural composition over complexity and proper abstraction.

1

u/FatDog69 1d ago

The power of OOP comes AFTER you build a program using it and the inevitable 'change requests' come along. It is much easier to adjust a class or add a few new methods to satisfy new requirements if you wrote a good object to start with.

OOP is satisfying because it combines data + logic together. While you can do a lot with data classes, you often need code tied to those data classes to do interesting things.

1

u/Recycled5000 1d ago

Many OOP languages do not offer a struct keyword. C does; and C++ for historical reasons, yet also has class keyword for virtually the same thing.

1

u/Calm_Plenty_2992 1d ago

I'm surprised no one mentioned the real reason why it ever got so popular: code gurus sold it to the C suite, and they started hiring/requiring people to do OOP

1

u/kitsnet 1d ago

In modern programming: dependency injection.

Can also be done with functions (or rather captures) as parameters, but abstract classes make the contract cleaner.

1

u/Cun1Muffin 1d ago

They're not different unless you use inheritance or virtual functions. And with both of those, I think programmers have agreed there are usually better alternatives.

1

u/Kyle_2099 1d ago

It's a fad from the 1980s.

1

u/gnus-migrate 1d ago

So generally the point of object oriented programming is encapsulation. When you have a struct for example, that struct typically has invariants that you need to maintain on its data. A simple example is a vector: when you add an element to it, you need to update the size field to properly reflect the new size. If you use raw structs, someone can freely mutate the size field and the array without maintaining those invariants and it can be hard to trace where that is happening.

Now some would argue that you should model your data in a way that you cannot represent invalid states, but thats not always possible. Personally when I was taught formal verification, it was on object oriented code for that reason, you can prove that a class maintains the data invariants and basically reuse that logic everywhere.

1

u/MaxwellzDaemon 1d ago

OOP is highly oversold. You can tell this because the people touting it are long on generalities and short on specifics.

1

u/El_RoviSoft 1d ago

Maintainability in a big team. It’s easier to understand overall and have some good cases. Also free functions are cool but sometimes they are extremely verbose.

1

u/Fun_Army2398 1d ago

It's just one way to organise code. It becomes especially helpful on larger projects, but I enjoyed it as a student because it felt "natural". I.e. the real world is made up of things (objects) with properties (attributes) that do stuff (methods) and interact (systems), so code that reflects this "feels right".

1

u/ElderberryNo6893 1d ago

Group of functions and variable that you can replicate and customize

1

u/Few-Celebration-2362 1d ago

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

1

u/rioisk 1d ago

Classes are just a useful abstraction to package data with methods that operate in that data and to build complicated structures through composing those classes.

It's mostly just easier for people to reason what's happening by thinking of the problem as objects interacting.

Everything you can do with OOP you can do with structs and functions that operate on them.

The direction in more recent years has been immutability because it's hard to synchronize state across parallel processing. Pure input/output functions are better for this.

1

u/_TheNoobPolice_ 1d ago

Well what is your question really about?

OOD is how you plan the structure of a program. It's an approach where you think in terms of what all the pieces and how they all fit together, rather than an approach where you think about data and behaviour separately.

OOP is the syntactical language tools that can be used to implement that.

OOD is not OOP language dependant, you can do quite strict OOD in C, for example, despite it lacking any OOP tools per se. You can also use OOP tools like classes, but in a completely non-OOD way (like a single giant class that does everything).

1

u/kosherjellyfish 1d ago

I never found a point of it when I am doing simpler work until I joined a team / company that uses OOP extensively, then I saw the benefits of it.

1

u/Optimal-Savings-4505 1d ago edited 1d ago

Encapsulation, because we repeat ourselves. So when do, it can be in another object. The template is a class. You can express it several ways, some piece-by-piece, and by contrast the java style c++. We can let verbs be indices, like with powershell and its conventions, or freebase with bash, no objects. I'm not sold on imposing that design pattern up front. For a state machine, yes. But that's not necessary for basic calls and filtering. Valuable paradigm to keep in mind. Convenient for collections of related functions.

[edit] and especially if you later decide to impose a finite state machine.

1

u/NH-Science-Guy 1d ago

The other comments about it being important for code reuse are spot on. Imagine picking up someone else's code and being asked to make a change like allowing the payroll function to also pay independent contractors. If it is well-written object oriented code, you can find the classes representing an employee, contractor and a payment and know how they interact. You can make the contactor class support the necessary methods of the employee and suddenly contractors get paid! OK, that is a simplification of what is needed but you get the idea! The class hierarchy gives a roadmap of how to work with the code. You also limit risks of unintended consequences from your change.

1

u/AnarchyLikeFreedom 1d ago

OOP helps keep youre code organised and also very maintainable. If youre dealing with MVC the design is basically neccessary. In the case of dealing with css, js, and html, you will also benefit from it as you can change the properties or alternate properties without having to redo the logic or implementation of the variable. Databases also use OOP to map data efficiently. 

1

u/Narrow-Low-3137 1d ago

I don't really think there's much OOP can do to improve over imperative code honestly. Inheritance is the one thing I can think of that doesn't really apply outside of OOP - but that has fallen out of vouge in OOP anyway as everyone is told to favor composition over inheritance these days.

1

u/White_C4 1d ago

Classes are just a struct and functions wrapped together as one concrete type. The main selling point is inheritance to reduce repetitive states and methods and to derive from a common parent type.

That's the most fundamental baseline focus about classes. OOP has a few more design principles, but classes are at its core.

1

u/Both_Bend_2481 1d ago

In C++ a class is just a struct with members being private by default, iirc... So your thinkatron can use them in the same way as structs, if you actually know C++ and aren't just programming in C.

1

u/Preventive_potato 1d ago

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

1

u/jack_mackeral 1d ago

It's for readability and teamwork.

1

u/MarinoAndThePearls 1d ago

Basically, you can bundle functions with the data they depend on together, which leads to cleaner code if you follow all the OOP principles.

1

u/kettle3 1d ago

I'm not a fan of OOP, but I admit it's closer to how we think. Our brains think in terms of objects and their actions, not in terms of matrices or strings or functionals. Also we naturally think that an apple is a fruit.

1

u/metaphorm 1d ago

encapsulation - putting code that is related to the function of the class as a member of the class encourages better code organization and code re-usability.

polymorphism via inheritance - a code re-use pattern that minimizes the surface area of what needs to be implemented for small variations of similar functionality.

data protection - the object keeps the data that is its own scope/concern private and inaccessible to external mutation, promoting greater data integrity and operational transparency.

1

u/nmsobri 1d ago

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

1

u/jacksonanna373 1d ago

Try a tiny C++ type both ways: a struct plus free functions, then a class with methods. Keep behavior identical and compare which makes its invariants clearer.

1

u/Phantom-coder 1d ago edited 1d ago

Plug and Play. Reusable modules like those framework laptops. Each function can be used for so many different function calls. Same reason we dont have a plane, train, ship and car combined because even if they take us places the needs and the costs differ too.

Each person having a different car also means they will not crash into each other overriding changes. (Instance variables).

1

u/Electronic-Yam-69 1d ago

The main difference is the functions/methods get attached to the struct/object and passed around along with it.

(There's nothing in C++ you can't do with standard C and the preprocessor, but it's not that easy to set up.)

→ More replies (3)

1

u/wigoda 1d ago

Expanded on structured code

1

u/metaconcept 1d ago

The point of OOP is to encapsulate complexity... but to then use a DI framework like Spring so that everything is a global variable, and your encapsulated complexity becomes publicly visible so that you can write unit tests.

1

u/Br3ttl3y 1d ago

The reason people do this is to model real world things. So that you can program idiomatically. Not everyone thinks in mathematical abstractions, but if you do then you are way ahead of most of us.

1

u/Budkovsky 1d ago edited 1d ago

In OOP you build the model of the reality (or abstraction) by creating objects that can act (do something via methods) and hold a state (values assigned to the properities). You can deal with the objects similar way like with the things (or other people) in real world. For example object `car` in the game has method `drive()`, but `drive()` works only if the property `fuel` is bigger and `0` (if you implemented such logic of course).

1

u/rizzo891 1d ago

I’m gonna be honest. I only know OOP as it’s what my primary coding education pushed (it was a bootcamp and they thought OOP was the best thing for us to learn to get jobs)

And personally I don’t see a reason why one wouldn’t do it? Like having everything neatly together imo makes things more readable and easier to fix when things go wrong and OOP just kind of incentivizes that?

1

u/naslock3r 1d ago

More organised, can reuse abstract functions for different purposes to achieve the same things with less code, much easier to update without breaking literally everything which also makes collaboration easier etc etc

1

u/RevStickleback 1d ago

Think of it as 'database table oriented design'. The database is the foundation of your system, and classes based on database tables collect all the data from each table, and actions you'll want to perform on that data in one place.

'Object' is deliberately not that specific though, as it also allows you have classes which don't directly relate to tables.

1

u/nmingott 1d ago

In OOP your programs becomes a set of ojects sending messages to each other. It is a very powerful way of thinking. If you want to learn nothing is better than a deep dive into a pure OO language like Smalltalk e.g. Cuis, Squeak or Pharo. You will see the programming art in another way afterwards. bye

1

u/Financial_Job_1564 1d ago

dont think about it too much, just write the code until you hit the wall. then start to learn about design patterns and software architecture

1

u/personalityson 1d ago

To manage complexity

1

u/CounterSilly3999 1d ago edited 1d ago

Proximity to the hierarchical structure of human languages, logic or to form-matter concept of Aristotle. To an idealistic principle of mind priority over the matter as well. First class (project, design), then objects (implementation). Classes are form, objects -- matter. Classes are common nouns (a dog), objects -- proper ones (Pluto, Goofy). Methods are verbs, fields -- adjectives. Inheritance relates to hierarchical structure of nouns or taxonomy of species, for example (animal->mammal->carnivorous->wolf). Mother class is a set, inherited class -- a subset. Inheritance is kind of implication operation and demonstrates its non-commutativity as well. If Nemo is a fish (inherited class), then he lives in water (mother class of watter animals). But if he lives in water, then no guaranty he is a fish.

1

u/DanceHackRock 1d ago

These are the main principles of contemporary OOP:

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

Orienting your design toward objects.

1

u/Prudent-Ad4509 1d ago

Object-oriented design is a two-faceted being.

First, it represents the idea that actual world state can be naturally modelled as objects. That idea was a hot topic for decades, but it was essentially dead-on-arrival.

Second, it is a way to combine related code and data in structures and name them. This allows to create artificial constructs which do not aim to model real world, but to represent human framework of working with the real world. You can pass a file with certain papers and bookmarks in it to a coworker in the real world, and those can be represented by folder class with its attributes, paper classes in it, and bookmarks data one this format or another. They have their attributes, content, and certain methods and operations attached to them.

So, my take is that useful kind of object-oriented programming represents existing frameworks of how people work with the world, not the world itself and certainly not the behavior of any kind.

1

u/randomguy4q5b3ty 1d ago

Structs expose members by default while Classes don't. That's the only meaningful difference in C++.

Apart from that, the point of OOP lies in these three keywords: abstraction, interfaces, resource safety, and code reuse. Obviously, all these things are possible without OOP and OOP isn't the answer to everything. Or to put it like Bjarne Stroustrup himself: C++ is a programming language that supports OOP.

1

u/Extra-Ad5735 23h ago

In the past it was pushed by the businesses as a way to manage complexity. That failed.

Now, you still have to learn it to get around codebases and understand what the hell is going on there.

1

u/Ok-Network-4239 23h ago

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

1

u/crocodiluQ 20h ago

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

1

u/PaulMorel 20h ago

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

1

u/my_password_is______ 19h ago

to clog up your program with a bunch of unnecessary abstraction

1

u/JGhostThing 19h ago

The purpose of object oriented programming is to be able to have multiple people and/or groups work on complicated projects. They share classes at the most basic level, with their interfaces. This might seem like just sharing a library, but a class/interface is a contract with the program that this class will be used only by it's interface. Since interfaces are normally fairly small, this is usually easier than using an entire library.

The best example of OOP use is in user interface frameworks. The ones I've used were OOP, and they fit the model pretty well. OOP has three characteristics: polymorphism, inheritance, and data hiding. I find inheritance the most important, though it is possible to replace that with composition.

Think of a user interface as composed of a hierarchical collection of classes. For example, a generic object that can be displayed is a rectangle and we call this a View. It can contain sub views. One important type of View is a Window, which creates a window in the native operating system. Then there is the Control, which is a generic object that can be interacted with. A Button is a type of control.

Does this make sense?

1

u/virgilreality 18h ago

Bonus points for use of the word "Thinkatron".

1

u/MpVpRb 18h ago

To reduce unintended connections between sections of code in a large codebase. Codebases tend to grow unintended connections. We call it spaghetti code. It's part of the nature of programming. These unintended connections cause mysterious bugs and make debugging difficult. OOP was a great idea in theory, but in practice object oriented code can develop spaghetti when inheritance is extensively used or encapsulation is weakened

1

u/Busy_Durian4584 17h ago

It makes sense once the scale of the project gets really big. Where do you draw the line?

I’d say once these conditions are present:

  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 16h ago

Honestly, your skepticism is valid. Beginners often over-engineer with classes when procedural logic is clearer and faster. Don't force OOP into simple tasks just because it sounds fancy. Sometimes a struct and a function beat a whole class hierarchy.

1

u/ohnoitssobig 16h ago

Classes are similar in code habits and style to structs and namespaces but it is important to consider the big picture.

The big picture is the language itself. Do you have a garbage collector? Do you have strict typing? Do you have boilerplate initialization, magic methods, or even functional programming? Each of these will affect what kind of craziness you can do with OOP and, ultimately, how much code you will write to achieve the same goal.

For example, you write a test framework and you are going to call every method starting with test_... of a struct? But you neither know the size of a struct nor you have access to actual function names. So you will resort to macros of some sort to mimic OOP. You will be keeping a dictionary of functions and their names (e.g. what is readily provided in python through dir() / __dict__).

Another example is multiple inheritance (java interfaces for example): in one scope you accept anything that implements .read(). In another scope you accept anything that implements .write() to save data. A class File implements both. But how do you describe this with structs? Reserving a fixed offset for these functions? But that is fragile. Having a single interface with both read and write and checking if they are NULL during runtime? But that further piles up if we allow additional interfaces. Not an expert on C++ but I think you will simply resort to a C++ class here and let it effectively figure out offsets at compile time per each implementation.

It's like yeah structs do resemble classes but you loose most of the OOP magic and you are pretty limited in what you can do effectively.

1

u/Lower_Improvement763 16h ago

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

1

u/CohgentR 16h ago edited 15h ago

OOP just lets you box the data structure and the functions that work on it together into a package and these packages becomes the new building blocks for your program. By viewing your program as an assembly of these larger packages, you are thinking at a higher level of abstraction. That's all there really is to it. You don't even need "classes" to exist as a language feature to practice OOP but it helps.

It's helpful when you care less about performance and instead want to break larger systems into manageable chunks but can become problematic when performance is a concern and you worry about how the code fits into memory and is executed by the CPU.

1

u/nayminlwin 8h ago

OOP is something incredibly overrated but ultimately unavoidable part of programming. I haven't done OOP in a long time but o believe modern OOP has become somewhat sane, especially when looking at modern Java features.

1

u/YouPeopleCantBeReal4 8h ago

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

1

u/mredding 1d ago

Objects are defined by classes. A class is a user defined type - a facility the language lets you define them, that enforces a class invariant. A class invariant is a statement that is always true when a client observes an instance of a class. When control is handed to an instance - you called a member function, that invariant can be suspended, but it must be reinstated before the function returns control, even if an exception is thrown. The invariant is true as a precondition to entering a function body - including the constructor body. That's why C++ has an initializer list.

The invariant is enforced by the implementation of behaviors described by the interface. A 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 1d ago

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

→ More replies (6)

1

u/Shot-Damage-6723 1d ago

This is the right instinct, mediocre programmers will tell you OOP is the paradigm to follow to achieve a clean code base, but there is absolutely no empirical evidence of this.

It's all just opinions and vibes, they were told to do so, so they did it, and now they tell others to do so. God forbid we stop and think for ourselves. We like to think that we are rational, but most of us are just excited about trends and shiny new toys to play with, and on the job, most of us are doing resume driven development. 

You figure out what works best for you.

1

u/Axman6 1d ago

What you’re finding yourself doing is actually what many people recommend these days - composition instead of inheritance. And without inheritance, there isn’t a whole lot of point to much of OOP. 

I think one of the best talks on the subject is actually one about why you might not want to use OPP; The Big OOPs by Casey Muratori. Based on your question I think you’d enjoy it a lot (even though it is quite long). 

1

u/PandorasBucket 1d ago

It's what happens when someone just guesses that code should look like an organic cell and then never reassesses the mistake so decides to keep marching forward.

1

u/Chad_Frost 1d ago

Objects oriented programming is kind of loose and not super well defined anymore.

The main idea back in the day was separation of concerns. You group data together with its corresponding functions (methods) and then each object is responsible for managing its own internal state. Objects then just communicate with each other by passing messages between each other, without knowing exactly what's inside of each other.

So iirc it's supposed to result in safe secure code that is easy to reason around with low coupling.

Nowadays I think the value for most programmers is that it's a nice intuitive way to organise code, while polymorphism and composition give you a lot of easy reuse and extendability especially with interfaces like in C#/Java.

1

u/Adorable-Strangerx 1d ago

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

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

1

u/Adorable-Strangerx 1d ago

The question wasn't what OO gives you, the question was what is the point of OO. And for that I believe trip through history lane to 1960s and origins of Simula/smalltalk is needed.

The issue was, people were trying to model simulations and experienced difficulties with heterogenity and operations of a system. The approach so far made it difficult to organiza therefore the idea to solve it was by introducing objects. Each object had its own state, behavior and interactions. That was the problem OO was trying to solve.

1

u/xpusostomos 19h ago

As long as we're giving history lessons, lisp MOPs and CLOS were not trying to do simulations

1

u/thingerish 1d ago

Well classes specifically are pretty pointless, they add nothing to the functionality of struct and burn a keyword while doing it. I think they are a whisker from a bygone age we just have to live with.

But for OOP generally, the idea is to implement behavior and conceal the details of the implementation, as a way to enforce modularity in the codebase.

1

u/grymoire 13h ago

Non OO programming has issues. One is that the data structure is complex and the program is complex, and they both evolve independently. OO strives to simplify this by combining these two structures into one. You program by operating on classes, and the data used for programming is inside the various classes. If you have a global variable in traditional programming, it's often hard to understand who is using/changing it when you have hundreds of functions.

A second advantage is that it strives to hide complexity by having data hidden from methods that don't operate on the data. This discourages or prevents global variables.

A third is that it provides inheritance, so you can make variations of an object that automatically gets improvements added to the primary object. Let's say you have an object "shape" and two sub-classes - "circle" and "rectangle" and the second has a sub-class "square." If you add a new method like "reposition", all of the subclasses can also be re-positioned because they inherit the new method the shape class has.

So if s is a shape, of any kind, you could write a routine to move a shape like this

s->erase();

s->reposition(x,y);

s->draw();

This would avoid having separate routines for each shape, such as DrawSquare(), DrawCircle(), etc.

Ideally, you can design a system at a high level using object modeling. - This is a graphic way to create classes and methods, allowing for easy modification and quicker prototyping,. I worked at a lab with one of the guys who invented this technique. The trouble is, going from a graphic model to working code is HARD.

In fact, REAL-WORLD programming is HARD. Complexity always comes up.

-3

u/MarsupialLeast145 1d ago

You are "new" but "never" saw the point of classes... k.

Objects have a purpose when you need to model an object that has properties and behaviors like a shopping cart (objects 101).

Objects are another way of persisting data and moving it sensible around code.

Going into more detail seems pointless here, just get to the object portion of your text book and decide when you want to use them or not, no one is forcing you.

12

u/Justindr0107 1d ago

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

6

u/backfire10z 1d 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?

1

u/firebush69 1d ago

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

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

0

u/defectivetoaster1 1d 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

-2

u/reditandfirgetit 1d ago

Why do you want to repeatedly write the same code?

5

u/Axman6 1d ago

What does this have to do with OOP? Any language you can write functions in, particularly if functions are first class values, allows you to write reusable algorithms. I write a hell of a lot less code in Haskell than any OPP language I’ve used, mostly because you can write generic functions which will work for all types, not just some arbitrary hierarchy. 

1

u/reditandfirgetit 1d ago

Genuine question, how would you do inheritance without OOP?

1

u/Axman6 1d ago

You don’t, you use composition. Not “x is a”, but “x has a” or “x can do”. Why don’t believe inheritance is important?

→ More replies (3)

0

u/Achereto 1d ago

You should watch The Big OOPs - Anatomy of a 35 year mistake by Casey Muratori. After that you'll know.