Keeping a library dependency-free
I have a small Utility library containing some useful utility methods which have been fully unit-tested. At the moment, my library has no external d开发者_C百科ependencies. I am toying with the idea of adding logging to my classes which might be useful for debugging purposes. But this would mean bundling logging libraries along with my project.
My question is: should I keep my library dependency free? Are there any advantages of doing so?
I would add a logging interface that the can be used to abstract the logging. Then the allow users to add logging via this interface. You too should use this interface, and you should supply a 'NullLogger' built into your library that would be used if no other logging is needed.
You can make it easy to not use the NullLogger by asking users to configure a new one, simply by config file or by run time discovery.
Use Java Logging. It's part of JRE/JDK so no external libs are needed.
Check out examples.
There are many advantages of doing so, not the least the ability to run on most any operating system.
One way of keeping your library pretty dependency free, is to require it to initialized prior to use. Then you would in your_lib_init(); function take a function pointer to logging backend. This means, the backend can be rewritten for any platform it might run on.
Also figure out, if you want a library totally free of all library dependencies, or one that depends on the standard class path. If it is pure Java, it will run on J2ME, Android, native compiled Java with GCJ and what not. If it uses class path, it will be portable across all class path implementations, in practice wherever OpenJDK runs.
Pro:
- Your library will be much smaller (chances are that you're only using a small part of the full functionality of any dependency)
- No update hell (like your code needs library C, version 2, product X needs your code and library C, version 1).
- You won't need to bend your spoon to the whims of someone else (say the library you goes from 1.x to 2.x -> you need to update your code)
Con:
- Wasted code if product X also needs the library
- How smart are you? Chances are that you can't match the thought, wisdom and time that already went into the library.
PS: If you want to support logging, add slf4j to your code; this is a 30KiB API which allows users of your code to use any logging framework out there. Do not use commons-logging.
精彩评论