3 ms·
Here's part of why the interface thing is useful: it gives you dependency injection almost for free, and it allows modules to be extremely decoupled. You can cr
by JulianMorrison 12y ago
Here's part of why the interface thing is useful: it gives you dependency injection almost for free, and it allows modules to be extremely decoupled. You can create a module-local interface describing not just a "generic X" but "specifically what methods of X I want". That way you don't even depend on other object's types, but only on their permitted actions. And making mocks is very easy. The IO libraries use this extensively; they don't depend on where you're getting your IO from. They just require it does this or that.
Bonus, you can define "tolerable minimum" and "nice to have" versions of the same local interface. Define your methods in terms of the first, but attempt to cast to the second.
if nice, ok := minimal.(Nice); ok {
// do stuff only possible with the nice to have interface
}
Example: the HTTP libraries will flush your IO if you give them something flushable, but they don't require it.