The previous article left an open question: how will RockPlayer find where to play each song, without tying the rest of the system to a specific provider? Today the answer is YouTube. Tomorrow it could be another one, and it is exactly that "tomorrow it could be another one" that the adapter pattern solves.
The problem, without decoration
If the code that decides the next song, records the like or dislike and talks to RockRecommender also knew the details of how to search for a video on YouTube, any change in that search (a new parameter, a different field in the response) would risk breaking business rules that have nothing to do with it. And testing that code becomes annoying: every test would need to call YouTube for real, with internet and everything, just to check a business rule that has nothing to do with YouTube.
The idea: separating "what I need" from "how I get it"
The way out is to have an interface that describes exactly what the rest of the system needs, without naming any provider: give me where to play this song. This interface plays the role of an entry port, whoever wants to find a song calls it, without knowing (or needing to know) what is on the other side.
How this looks in RockPlayer
public interface IMusicProviderAdapter
{
Task<Result<PlaybackSource>> FindAsync(string band, string title);
}
public sealed record PlaybackSource(string Url);
This PlaybackSource is still quite lean, just a URL, and it will grow a bit further along the series, as the screen actually needs more information to show. Exactly like RockRecommender's RecommendationService never knows about MongoDB, only the ISongRepository interface. Who actually talks to Mongo is the implementation of that interface, hidden inside Infrastructure. The controller doesn't even get to know that any repository exists.
Why this pays off here
In article 6 of this series we create a new class implementing this same interface and register it in dependency injection. That's it. Nothing that already exists needs to change, and that is exactly what I want to show you happening for real there. The next article covers a different piece of the theory: how RockPlayer avoids asking the music provider the same thing twice, without a database.