Skip to content

Deref not necessarily an antipatternΒ #403

@blueglyph

Description

@blueglyph

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'd 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 surprising idiom when used with this idea in mind than when using it for other wrappers in general, like smart pointers, or blanket implementation of traits. There are other uses, not dissimilar to smart pointers, which can greatly benefit from such pattern, one of which is the "newtype" practice that is necessary to work around the orphan rule.

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.

EDIT: This part of my initial issue about poor "foo-bar" non-illustrative and confusing examples has already been reported here, as mentioned in the next comment, so I removed it:

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?~~

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions