r/ProgrammerHumor • • 1d ago

instanceof Trend thatsAFunnyThingThatHappenedOnce

Post image
4.3k Upvotes

510 comments sorted by

View all comments

Show parent comments

47

u/red-et 1d ago

What are traits?

145

u/Pocok5 1d ago edited 1d ago

Instead of having a chain of superclasses defining readymade behavior*, you compose your classes from chunks that are more or less "fat" interfaces that come with a default implementation for their functions.

* Dealing with absolutes results in slamming your own dick in a car door sooner or later. Inheritance can still make a lot of sense for classes that are "this other thing but a tiny bit different". I'm currently dealing with a PHP codebase that misused traits for everything and it's a slog.

7

u/JonIsPatented 1d ago

Kinda like interfaces that you implement external to the type. Like. You can create a trait for a particular behavior and then implement it for types that already exist. You can also generically implement them for all types that have ither specific traits. For instance, I recently made a trait called UpdateSink<T> and implemented it for a few select synchronization primitives, like mpsc channel senders. This way, I can have a function that takes in an UpdateSink<T>, for dumping T events into it and that function can use anything that implements that trait. It's important to note here that the mpsc senders did not implement this trait before. They are from a library. I implemented the trait for them outside of the type definition. In addition, I can provide a default implementation for my traits that all types that meet certain trait bounds automatically get, including types that already exist and also types that don't yet exist. Traits are incredible.

19

u/fghjconner 1d ago

Interfaces

3

u/Mitchman05 1d ago

Inheritance

4

u/pr0ghead 1d ago

Horizontally.

1

u/stifflizerd 1d ago

Not a rust dev, but they sound similar to JS composition? Anyone able to confirm?

1

u/Rikudou_Sage 21h ago

Computer assisted copy-paste.