logoalt Hacker News

jqpabc123last Saturday at 2:29 PM4 repliesview on HN

Inheritance may have some limited utility but it often degenerates into "spaghetti code" dressed up to appear modern and acceptable.

Just like "goto" in the days of old, it is best used sparingly.


Replies

WCSTombslast Saturday at 5:18 PM

There's a now well-known guideline that says "prefer composition over inheritance." When I saw that, it clarified a lot of things. While much of software design can theoretically be approached in terms of class hierarchies, that's rarely the right place to begin, since after you start preferring composition, inheritance is mostly just a tool to achieve polymorphism.

It's a bit of a tangent, but I think the "class Dog extends Animal" type of tutorial did a lot of damage to impressionable programmers. Because it's completely abstract and basically meaningless, it's impossible to look at it critically and discuss why you would choose this or another approach, so the idea of class hierarchies just becomes a sort of dogma (so to speak).

show 3 replies
llmslave2last Wednesday at 7:25 AM

Inheritance is great, just depends how you use it.

I've never once reached for it for building servers.

For games? All the time.

show 2 replies
bheadmasterlast Wednesday at 7:29 AM

Inheritance is often used as an enabler for polymorphism in languages that don't support it in any other way.

Somehow, it leaked out and convinced everyone that it is a good thing on its own.

show 2 replies
atoavlast Wednesday at 8:03 AM

So it is good that most Rusts introductions tell you that you should favor composition over inheritance in multiple places:

https://rust-for-c-programmers.com/ch20/20_3_rust_s_approach...

If Rust pushes any concept it is the use of traits: https://rust-lang.github.io/book/ch10-02-traits.html