5 ms·
In Haskell, we call this problem "overlapping instances," and can be allowed with an optional compiler flag. Nevertheless, I try to avoid using it, because of t
by hackyhacky 1y ago
In Haskell, we call this problem "overlapping instances," and can be allowed with an optional compiler flag. Nevertheless, I try to avoid using it, because of the potential for unforeseen consequences and reduced clarity in which code is actually being run.
In this use case, my instinct tells me that trait specialization is the wrong tool for the job. The author is trying to dispatch different functions based on a flag set in the caller. I can think of two more elegant ways to do this:
* Make the file system itself a trait, with implementations for read-only and read/write. Pass the concrete implementation as a parameter to the function using it.
* Store the capabilities as a variable in the file system object and query it at runtime. This can be done with an if.
Sometimes the simpler approach is better.
- nesarkvechnep 1y agoYour proposal might work but then the user won’t have the compile-time guarantee that they can’t try to write to a read-only filesystem, since the capability will be queried at run-time.
- dwattttt 1y agoI may be misunderstanding, but > Make the file system itself a trait, with implementations for read-only and read/write Those are separate concrete implementations between read-only and read-write; a write operation can be implemented on the read-write implementation only.
- nesarkvechnep 1y agoIf the filesystem is a trait which has a read and write method. Your concrete implementations have to implement both.
- dwattttt 1y agoSo... Don't give the trait methods that don't apply to every member of the trait. Only implement write methods on the concrete Write implementation.
- nesarkvechnep 1y agoSo… you lose the ability to have a generic parameter which implements the trait. You need to know the concrete implementation in order to know if there’s a write method, for example.
- dwattttt 1y agoIt doesn't sound like they're making multiple implementations that can write? If they were, they could make a trait for a Writable fs. But from their description it sounded like exactly two concrete implementations, one read-only, one read-write. If you want to share code or implementations, there's lots of ways still. For example, if the read-write filesystem implementation is a superset of the read-only, put a read-only struct inside the read-write.