In a previous blog post, we demonstrated how capabilities could be used to elegantly solve the problem of having multiple logging frameworks on the classpath.
In this post, we will again use this concept in a different context: optional dependencies.
Sometimes I need a public static constant of a class. For example:
org.springframework.http.HttpHeader.ACCEPT
So I make spring web a dependency. I then puts an extra 20MB of dependency like spring core and others into my application. So I have to exclude everything explicitly.
Here comes optional into the picture. If a library is written with dependencies marked as optional, you can use anything from that library without negative consequences.
Usually a developer uses a “util” library for extending the capabilities of an already included dependency.
A util library collection often contains several “extensions” for several indipendent frameworks. A developer usually needs one or few features from it. And do not want to deal with excluding dependencies they do not need… In contrary a developer always knows which feature he needs and if it has additional optional dependency which is required, he always can insert that dependency directly into his project.
Optional is there for a reason for several years now. Stating that a widely used framework (maven in this case) is bad and we are way smarter than the people designed it shows arrogance not competency…
Yes, for this purpose compileOnly (a.k.a. optional) dependency seems like a perfect fit. No need for exclusions down the line.
I haven’t seen the article stating “optional is bad” but pointing out “multiple problems” with it, and providing alternative (rather neat, in my opinion) solution. In the end, you could choose either way to declare the dependencies of your module having in mind how you want its users to consume it.
Hi
I realised this week, that using the main source set for a feature is deprecated.
Can you elaborate on why?
I think for the use case of an optional dependency it was quite useful to be able to publish one lib but different sets of dependencies to make certain features usable…
Thank you.