Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Foo Bar (ad nauseam) #403

Open
blueglyph opened this issue Apr 7, 2024 · 0 comments
Open

Foo Bar (ad nauseam) #403

blueglyph opened this issue Apr 7, 2024 · 0 comments

Comments

@blueglyph
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant