Static version of an object

I am developing a website using struts2 framework.

I just need guidance on when to use static methods and when to instantiate an object for a class.

For example: in my database connection I am using a singleton, so there will only be one database connection per user (is that correct?) And I think if I have a class, let's say it is a class full of methods intended only for manipulating data from the database. Should I make these methods static as well? Or should I make the class singleton as well, so my application will only have one instance of the class full of methods?

+3


source to share


2 answers


Static methods are good for "pure functions": those pieces of code that are independent of the configured runtime state and have no side effects.

A method that fits the above description can be easily tested on its own, since it doesn't have any dependencies that you should ridicule, and it also doesn't make sense to mock its functioning.



Sometimes even functions matching the description above can be useful from the instance methods of the service object, because in this way polymorphism can be used to override some behavior. Personally, I never had a need for this, because the methods that I choose to implement as static methods are such that they only have one meaningful implementation.

Also, factory methods essentially need to be static as they are instances that provide instances. factory methods can be simple (some convenience around constructors) or have dependencies, especially in some configuration. In client code, you can avoid heavy weight factory methods by relying on the Dependency Injection framework, but usually a stand-alone library will offer an entry point to its API by providing a static factory method.

+1


source


Once you start talking about static

and singlons in the context of a web application, you are now talking about concurrent access to the static

/ singleton tag , which can be a potential problem in two ways:

  • There is not enough thread safety and you will have problems such as illegal sharing (possibly with a database connection), data corruption, race conditions, etc.
  • Too much thread safety and you will kill concurrency, with accessing the shared resource static

    becoming the bottleneck synchronized

    for everything in your application


In general, you should avoid static

in any multi-threaded environment (like a web application). The fact that your static

thing is a database connection presents additional problems, but also a solution. Use a third party database connection pooling like c3p0 , DBCP or similar. Then you don't have to worry about managing either singleton or concurrency at all. The pool will be smart enough to take care of everyone.

0


source







All Articles