Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2019
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. /// Problem: there is a lot of duplication in function implementations.
  2. /// The two types should have the same interface but use a different underlying type.
  3. ///
  4. /// How can I reduce the amount of duplication and avoid having to update the code in two places?
  5. /// In other languages, I would define a base class which accepts a generic type for the `SoundSource`s
  6. /// but I don't know how to solve this sort of problem in Rust.
  7.  
  8. struct Sound {
  9. // Shared properties
  10. is_playing: bool,
  11.  
  12. // Sort of shared
  13. source: SoundSource,
  14. }
  15.  
  16. struct SpatialSound {
  17. // Shared properties
  18. is_playing: bool,
  19.  
  20. // Sort of shared (is a superset of SoundSource in terms of interface)
  21. source: SpatialSoundSource,
  22. }
  23.  
  24. impl Sound {
  25. fn play(&mut self) {
  26. self.stop();
  27. self.play_later();
  28. }
  29.  
  30. fn stop(&mut self) {
  31. self.source = SoundSource::new();
  32. self.is_playing = false;
  33. }
  34.  
  35. fn play_later(&mut self) {
  36. self.source.play_later();
  37. self.is_playing = true;
  38. }
  39. }
  40.  
  41. impl SpatialSound {
  42. // Duplicate of Sound::play
  43. fn play(&mut self) {
  44. self.stop();
  45. self.play_later();
  46. }
  47.  
  48. // Duplicate of Sound::stop but with a different type
  49. fn stop(&mut self) {
  50. self.source = SpatialSoundSource::new();
  51. self.is_playing = false;
  52. }
  53.  
  54. // Mostly duplicate of Sound::play_later
  55. fn play_later(&mut self) {
  56. self.source.reset_position(); // Here's how it differs
  57. self.source.play_later();
  58. self.is_playing = true;
  59. }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement