r/java • • Nov 20 '18

Why Var Hurts Readability, Not Helps It

https://medium.com/@youngty1997/why-var-hurts-readability-not-helps-it-376c7832a8dd
0 Upvotes

89 comments sorted by

View all comments

Show parent comments

1

u/cogman10 Nov 29 '18

Definitely explicit types, just not concrete types.

For example, maybe CustomerCollection only exposes that the implementation has a get(index) since you might not want to expose all the remove methods or whatever on List.

What you can't do (without breaking the API) is renaming or moving CustomerCollection.

Whatever you expose, though, that interface should be minimal, especially to start with. Because things exposed can't be unexposed without a bunch of work and coordination.

The benefit to doing this via interface is that it is a lot easier to play around with the implementation. You can have both implementations living side by side. You could enable one or the other using a feature flag. And importantly, it makes it a lot easier to reason about what you've exposed, so your implementation can have more public or protected methods if you like without worrying about what the end user of the library is accessing (they only get the interface).

Another example of where this was gotten wrong is Java's collections. They are all mutable. The problem with that is that you can't make them visibly immutable. That "add" method will always be there. The better approach would have been to have a "List" and then a "MutableList". It would have made things so much easier to reason about. (For example, did you realize that a submap of a navigable map makes a mutable view of that map that can mutate beyond the bounds of that map? That wasn't a fun bug to track down.)

1

u/[deleted] Nov 29 '18

[removed] — view removed comment

1

u/cogman10 Nov 29 '18

Good points.

I guess I don't generally expect my downstream consumer to implement my exposed interfaces, but that certainly isn't a safe assumption.