Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

The answer is simple: Traits

The weakness of OOP structurally stems almost entirely from inheritance, which I think is very poor construct for most complex programs.

How should the widget situation be handled? Well, what is a widget? It's hard to define, because it's a poor abstraction.

Maybe all your "widgets" should be hide-able, so you implement a `.hide()` and `.show()` method on `Widget`. Oh, and all your widgets are clickable, so let's implement a `.click()` method.

Oh wait.. but this widget `some-unclickable-overlay` is not clickable, so let's build a `ClickableWidget` and `ClickableWidget` will extend `Widget`. Boom, you're already on your way to `AbstractBeanFactory`.

We got inheritance because it's an easy concept to sell. However, what if we talked about code re-use in terms of traits instead of fixed hierarchies?

So, our `some-unclickable-overlay` implements Hideable. Button implements Hideable, Clickable. We have common combination of these traits we'd like to bundle together into a default implementation? Great, create super trait which "inherits" from multiple traits.

Rust uses such a system. They don't have classes at all. Once you use a trait system, the whole OOP discussion becomes very obvious IMO.

1. Shared state can be bad, avoid if possible

2. Inheritance is a poor construct, use traits, interfaces, and composition instead.

3. Don't obsess about DRY and build poor abstractions. A poor abstraction is often more costly than some duplicated code.

4. Use classes if they're the best tool in your environment to bundle up some context together and pass it around, otherwise don't



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: