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

Nice article, but I'm not sure I like using the Deref trait just to make code "cleaner" - it does the opposite IMO, making it harder to understand what's going on.

Deref is convenient for builtin "container" types where the only thing you'll ever do is access the singular value inside it. But sprinkling it everywhere can get confusing ("why are we assigning a &str to a struct here?")



In addition to containers, it seems to be useful for 'wrapper' types adding decorators to the 'base' object without having to wrap/unwrap the new type in each operation.

Classic OOP would use inheritance to achieve this, while something like Deref allows you to use it with all the added behavior - without losing the possibility to assign to it values of the base type.


A good discussion of why using Deref to simulate inheritance is considered an "anti-pattern": https://rust-unofficial.github.io/patterns/anti_patterns/der...


In general, I don't like the term "anti-pattern" or its sibling "best practices". Those terms give off an authoritative aura instead of spurring curiosity, and often people don't seem to remember the rationale but just associate X with absolute bad and Y with absolute good.

Softer language like "guidelines" and "recommendations" or playful language like "tricks" or "hacks" seems more useful to me. "Hacks" is dirty and _interesting_ instead of normative and unquestionable.


Thanks for this; I saw it, and it made me twitch, but I didn't know why... All I had was "composition over inheritance"




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

Search: