The construct Resources.toString(Resources.getResource("foo"), Charsets.UTF_8) feels a little cumbersome. Why the insistence on conversion to URL’s first? Since the getResource() method doesn’t throw an exception, why not have parallel String methods as well?
The construct Resources.toString(Resources.getResource(foo), Charsets.UTF_8) feels a little cumbersome. Why the insistence on conversion to
Share
I’m pretty sure this all comes down to orthogonality and composability. The API clearly separates getting the
URLof a resource from doing something with that resource. This is important because there are a number of ways that you can get theURLof a resource.Resources.getResource("foo")is one, but it just won’t work in some situations. If you need to ensure that a specificClassLoaderis used (because Guava may be loaded by a differentClassLoaderthan your application files), you need an alternative way of getting theURLsuch asResources.getResource("foo", SomeApplicationClass.class).If
Resourceswere to provide overloads of its methods to handle all those cases, the number of methods in the class would triple. That might seem acceptable in this particular case, but if similar “shortcuts” were added throughout the library, the number of methods would balloon up very quickly. The library would become much more difficult to digest because you’d have to dig through a sea of methods that do almost the same thing to find what you want. For that reason, Guava favors powerful methods that do one thing and which combine well with other methods. CombiningResources.toStringwithResources.getResourceis an example of this.Of course, that doesn’t mean that Guava never provides such shortcuts… it just only does so when the addition really seems worth it. For example, most of the methods in the
Filesclass could be removed since you can just combineFiles.newInputStreamSupplier,Files.newWriterSupplier, etc. with the methods in theByteStreamsandCharStreamsclasses to accomplish the same things. Given how common operations onFiles are, though, the shortcuts were deemed worth it. (Note that overloads that take aStringfilename were not added, though.)