rust-unofficial / patterns

A catalogue of Rust design patterns, anti-patterns and idioms
https://rust-unofficial.github.io/patterns/
Mozilla Public License 2.0
7.84k stars 352 forks source link

Foo Bar (ad nauseam) #403

Open blueglyph opened 2 months ago

blueglyph commented 2 months ago

In src/anti_patterns/deref.md:

There is no struct inheritance in Rust. Instead we use composition and include an instance of Foo in Bar (since the field is a value, it is stored inline, so if there were fields, they would have the same layout in memory as the Java version (probably, you should use #[repr(C)] if you want to be sure)).

In order to make the method call work we implement Deref for Bar with Foo as the target (returning the embedded Foo field). That means that when we dereference a Bar (for example, using *) then we will get a Foo. That is pretty weird. Dereferencing usually gives a T from a reference to T, here we have two unrelated types. However, since the dot operator does implicit dereferencing, it means that the method call will search for methods on Foo as well as Bar.

I've skipped the code, and it goes on like that in the following paragraphs.

There's a tendency for people to abuse the Foo/Bar to avoid looking for an educational example, especially in Rust. It saves the writer time and effort, but reading this really makes little sense. Using evocative names will make it much easier for the reader to understand and memorize the concept, because that's how our brain works. 🙂

Why not use a wrapper around, say, HashMap, and use Deref to override a method like insert that checks a requirement, modifies the data, or stores a complement of information?

I'd also argue that it's not such an antipattern. The idea of Deref is giving some transparency to a wrapper, which is what we're doing here, and Deref isn't more of a suprising idiom when used with this idea in mind than when using it for other wrappers in general, like smart pointers. If one argument had to play against this practice, it would be point 2 of the "shouldn't" part in the Deref documentation: method name collision — which would be better illustrated with a practical case like HashMap::insert() than random foobarness.