Hacker News new | ask | show | jobs
by jfengel 281 days ago
Why would you want that? The whole point of an interface or superclass is to let you swap implementations without changing everything.

I also like the nudge it gives you to use only the higher level methods, rather than the ones specific to the subclass unless they're needed. That also improves flexibility.

1 comments

It’s not about swapping implementations, like the original poster suggested, so that you can later come in and swap out different implementations in a local sense. Interfaces are used to decouple parts of an application; for example mocking test interfaces. Another way to look at it is that interfaces are a contract that needs to be fulfilled.

Declaring a local variable as an interface to hide functionality so you can swap out functionality later is misunderstanding the fundamental theories around interfaces. Your variable should be whatever the function or method returns. If you want to abstract the type so it can be swapped out, create a function that returns an abstract type. Don’t tell the HashMap constructor it did the wrong thing. Now that I think about it, I’d recommend you use “var” in all cases, and not try to redefine the return values from a function.