this post was submitted on 16 Jul 2023
1267 points (98.8% liked)

Programmer Humor

32563 readers
584 users here now

Post funny things about programming here! (Or just rant about your favourite programming language.)

Rules:

founded 5 years ago
MODERATORS
 
you are viewing a single comment's thread
view the rest of the comments
[–] magic_lobster_party@kbin.social 35 points 1 year ago (1 children)

OOP can be good. The problem is that in Java 101 courses it’s often taught by heavily using inheritance.

I think inheritance is a bad representation of how stuff is actually built. Let’s say you want to build a house. With the inheritance way of thinking you’re imagining all possible types of buildings you can make. There’s houses, apartment buildings, warehouses, offices, mansions, bunkers etc.. Then you imagine how all these buildings are related to each other and start to draw a hierarchy.

In the end you’re not really building a house. You’re just thinking about buildings as an abstract concept. You’re tasked to build a basic house, but you are dreaming about mansions instead. It’s just a curious pastime for computer science professors.

A more direct way of building houses is to think about all the parts it’s composed of and how they interact with each other. These are the objects in an OOP system. Ideally the objects should be as independent as possible.

This concept is called composition over inheritance.

For example, you don’t need to understand all the internals of the toilet to use it. The toilet doesn’t need to be aware of the entire plumbing system for it to work. The plumbing system shouldn’t be designed for one particular toilet either. You should be allowed to install a new improved toilet if you so wish. As long the toilet is compatible with your plumbing system. The fridge should still work even if there’s no toilet in the house.

If you do it right you should also be able to test the toilet individually without connecting it to a real house. Now you suddenly have a unit testable system.

If you ever need polymorphism, you should use interfaces.

[–] AstralWeekends@lemm.ee 2 points 1 year ago

This was a nice analogy, thanks for the write-up.