Hacker News new | ask | show | jobs
by vbezhenar 3030 days ago
I don't like the fact that `var` breaks class hierarchy. I can write `List l = getList()` and then variable `l` will have only methods from `List`. If I'll decide to change `getList()` return type, it'll be easier to migrate the code. With `var` variable `l` probably will have something like `ArrayList` type and I can accidentally use methods from `ArrayList`, even if I don't really need them, tying this code to concrete class.

It's obvious that everyone will use `var` everywhere, so using `var` in one place and explicit type declaration in another probably would be even worse.

1 comments

The problem here is not the `var` keyword but the `getList()` method that is leaking implementation details by having a concrete class return type instead of an interface.
But it's a good style: return concrete class, so if I really need those implementation details, I can have them without casts and potential runtime errors. Return as concrete type as possible and declare variable for holding this result as abstract as possible.
I disagree that this is a good style in general.

If I commit to returning an ArrayList then it's not backwards compatible if I want to change to a different concrete List. My experience has been that if you return a concrete class then people will rely on those details even when they don't need to. And if you're writing a library that others depend on then you don't even know how they're using your returned value.

Of course if people are doing unsafe downcasts because they need the guarantees of a particular implementation then you should just return the ArrayList directly. And fortunately this change is backwards compatible, so there's no need to worry!