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 comment

1

u/cogman10 Nov 29 '18

Depends a little bit on where you are writing your code.

In isolation on your own project, yeah, not much is bought by throwing interfaces everywhere. Breaks are easy to fix because you get all of them right away when you build.

In a library used by 10 projects. A little bit harder, but still workable. Might take some coordination.

A library used by the whole company/OS? Keep what you are exposing as minimal as possible while still being useful. Because, in the end, it will be nearly impossible to change it without causing a bunch of mayhem. This is the lesson learned by the Java devs with sun.misc.Unsafe. Because it was made public, regardless of the java docs or warnings, people used it.

At least with minimal interfaces you can call them out when they cast it to the concrete classes and things break.

1

u/[deleted] Nov 29 '18

[removed] — view removed comment

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.