Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// Problem: there is a lot of duplication in function implementations.
- /// The two types should have the same interface but use a different underlying type.
- ///
- /// How can I reduce the amount of duplication and avoid having to update the code in two places?
- /// In other languages, I would define a base class which accepts a generic type for the `SoundSource`s
- /// but I don't know how to solve this sort of problem in Rust.
- struct Sound {
- // Shared properties
- is_playing: bool,
- // Sort of shared
- source: SoundSource,
- }
- struct SpatialSound {
- // Shared properties
- is_playing: bool,
- // Sort of shared (is a superset of SoundSource in terms of interface)
- source: SpatialSoundSource,
- }
- impl Sound {
- fn play(&mut self) {
- self.stop();
- self.play_later();
- }
- fn stop(&mut self) {
- self.source = SoundSource::new();
- self.is_playing = false;
- }
- fn play_later(&mut self) {
- self.source.play_later();
- self.is_playing = true;
- }
- }
- impl SpatialSound {
- // Duplicate of Sound::play
- fn play(&mut self) {
- self.stop();
- self.play_later();
- }
- // Duplicate of Sound::stop but with a different type
- fn stop(&mut self) {
- self.source = SpatialSoundSource::new();
- self.is_playing = false;
- }
- // Mostly duplicate of Sound::play_later
- fn play_later(&mut self) {
- self.source.reset_position(); // Here's how it differs
- self.source.play_later();
- self.is_playing = true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement