5

I'm writing java library(jar file) to log Web service request and responses in a Database for in-house application. This library will have two methods registerReuqest and registerResponse.

I'm wondering is it good idea to pass database connection to these library methods?

Passing connection to library will have some pros and cons.

Pros: One connection can be used to register request and response, both of them. This decrease delay of opening second connection. In some cases, caller service will use the same connection too.

Cons: Caller service and library becomes coupled.

4

is it good idea to pass database connection to these library methods?

Counter-question: If you don't pass the connection in, then how is the library going to open a connection to the database for itself?

Which database?
How is it configured?
Where is it configured?

If these are not things you want the library to worry about, then pass it a connection to use.

2

Judging from the IoC tag in your question, I would assume you are using an Inversion of Control container of some kind, so to answer your question, No you should not have applications directly pass a database connection to your library.

Instead, you should utilize Dependency Injection. Your software components that require a database connection should be constructed/initialized by your IoC container and this will inject the required dependencies needed by your software components.

On the concerns about contention on database connections, this is a well solved problem by utilizing a database connection pool. Instead of requiring a database connection, require a database connection pool that your software components can request a connection from, then return back to the pool when done. This allows the application using your library to configure the details of the pool and optimize it for their needs. It would not be your problem to worry about at this point.

0

The calling application has to pass something to the library, but typically these are properties or a configuration required to instantiate a connection which is used internally by the library, but not the actual connection itself. The library will take the configuration and create the connection, manage it's lifetime, etc. The connection should not be exposed.

A typical configuration will be properties like:

  • Server Name
  • Port
  • Database Instance
  • Id/Password

Your application would store the connection properties in it's own configuration file as it knows which database it needs to connect to and pass those library.

In your cases, the library can internally manage the lifetime of the connection for the request/response calls as needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.