I have following scenario, and a confusion to have instance method or static method for dbhelper?
We have a dbhelper class which as name suggest help other classes to work with MySql db.
The db helper class will be used by 2 independent module.
Java Webapp.
Windows based Java app
Currently all the methods in dbhelper class are instance methods
There are 8 methods in dbhelper class among which 3 will be common for webapp and windows app and rest only used by webapp.
Windows app is kind of continuously running 24*7.
Our confusion is such that if we keep methods as instance methods, then we have to crate object of dbhelper class and eventually will be always alive as used by windows app.
What I see advantage of keeping methods as static is no object required.
Note:
I know how static and instance method works.
Google search do not help for this specific example.
The question is too broad for a specific answer. But I can answer with the kinds of things I'd be thinking about, in general.
First of all, if your static methods are going to save state in static class variables, that's not good practice. If there's any state involved, you definitely want to make them instance methods, so that an object of that instance will be holding the state.
You mention that your methods are there to help work with a database. How are they going to access the database? If the database isn't passed as one of the method parameters, then that means the reference to the database has to be stored somewhere, and I think it's best if the dbhelper is an instance that stores a reference to the database (or a reference to some other object that can be used to retrieve the database object) as one of the instance fields.
So I'm going to assume that the methods take a database parameter, or a parameter to some other object that will give you the database object. Given that, there are two things I'd think about when considering whether to make your methods static.
(1) What is the likelihood that the method will change because the requirements change? If it's at all likely, then I'd definitely lean toward making the methods instance methods; in fact, I'd consider making "dbhelper" an abstract class or interface, and having different implementation classes implement the abstract methods in different ways when something changes. That seems to me to be more flexible than just having one static class whose code has to change if the business logic changes. It lets you switch back and forth, or even lets you switch the logic dynamically at run time.
(2) Will you want to mock the method for testing? If your methods access a database, then you will probably want to provide a mock version of the method when unit-testing other classes that call the method, since you want to be able to test them without worrying about setting up the database access and everything. This would also argue for making dbhelper abstract or interface, so that you can provide a mock implementation in addition to your real implementation. (However, some testing platforms like JMockit will let you mock static methods.)
Those are the kinds of things that would lead me toward making the methods instance methods. If you're sure that they don't apply, then it should be OK to make them static methods.
Instead of using static, make use of Singleton design approach for dbHelper class.
something like this,
public class MyDBHelper {
private static MyDBHelper instance;
private MyDBHelper(){}
public static MyDBHelper getInstance(){
if(instance == null){
instance = new MyDBHelper();
}
return instance;
}
public void addRow() {
........
}
}
From other classes, you can access the methods like below
MyDBHelper.getInstance().addRow();
1st : Make all methods of class dbhelpe static and load them when your application gets loaded by any web/application server.This task can be accomplished by static block .
2nd : try to implement Singleton pattern on your dbhelp class ,so that only one object of your class can be shared,this will not leads your application to create object many times,and your application will work faster.
First of all, methods in one class used by multiple callers (web app and Windows app) suggests violation of SRP, so you should be dividing the single DB helper into multiple classes.
Secondly, there are advantages and disadvantages of static and instance methods.
If you practice TDD or DI, it discourages static methods as they are non-mockable (unless you use a framework like Powermock which to me seems a bit hacky.)
If you only do end to end testing, its okay to use static methods.
Related
I'm working on an existing piece of simulator software, and the structure is basically like this (it has a static member variable containing itself):
public class Simulator {
private Static Simulator instance;
public Simulator(){
instance = this;
//blah
//blah
//other things
}
}
And then a lot of methods access the static instance of the Simulator like this:
for(Foo f : Simulator.instance.getFoo() ){
//blah
}
You get this idea. Basically, the programmers who came before me assumed that there would only ever be one single instance of the Simualtor, so they made it accessible statically.
The problem is that I now want to run multiple instances of it, so this static part is becoming annoying.
Making this work without it being static is probably the best option, I know, but as you can imagine it will take a lot of refactoring and time.
The one thing that does work is to run multiple main methods (so run it several times in my IDE, or run it as a .jar in separate windows). I assume this is because each main method or JVM instance or whatever is acting as a sort of container, so the statics don't interfere?
What I was wondering was, is there a hacky workaround that I can use (at least short-term) to create multiple instances of the simulator, but within some kind of container that makes the static instances not interfere.
I think this is possible using Java class loaders (ClassLoader), but this will lead you into a world of pain. You would have to create sub-applications each using different class loaders. I have never done this, but I believe this is how application servers work.
It will be far easier to refactor your application.
Instead of accessing instance you would have to create multiple instance variables or some dynamic registry like a map where you store the references.
By-the-way, the way that instance is stored in the constructor is very bad practice as it will get overwritten each time new is called and the previous version will be lost. Usually, you would want to just initialise instance with an object.
The quickest and hacky way that I could think of is to override that constructor with a dummy variable
public Simulator(Boolean isDummy){
}
Now you have the option to create a multiple instance of that class without affecting others. Not sure if the parameter overhead is acceptable in your case.
I have a singleton class.
When accessing the methods of the class I have the choice of two possibilities.
Create those methods as instance specific and then get the instance and invoke them
Create those methods as static and invoke them and they will get the instance
For example:
Class Test{
private int field1;
Test instance;
private Test(){};
private Test getInstance(){
if (instance == null)
instance = new Test();
return instance;
}
public int method1() { return field1;}
public static int method2() {return getInstance().field1;}
}
Now, elsewhere I can write
int x = Test.getInstance().method1();
int y = Test.method2();
Which is better?
I can think of a 3rd alternative where I use "instance" directly in the static method and then capture the exception if it is null and instantiate it and then re-invoke itself.
I could, in theory, just make the whole lot static.
However, this will create me problems when saving the state at activity close since the serialization doesn't save static.
I think the first one is cleaner.
However, keep in mind that under some extreme cases, Android may kill your static instances. See this for example: http://code.google.com/p/acra/ .
A workaround I've found somewhere for this, is to keep a reference to your singleton from the Application class, as well. I don't know how problem-proof this is, though.
You should avoid making everything static. Some people would even say that a singleton is not done.
The whole point of the singleton pattern is that you can change the implementation. In most cases you use it to keep the possibility open to "hook" in some other implementations of this functionality later.
Read: when deciding in favor of singleton plan for a setInstance method too, not just for a getInstance. - If this does not make sense, just use a plain static class.
In the other hand singletons are out of season, if you want to be hip and all that. Do a search for "eliminating global state". There are some Google-sponsored talks about it too. In short: your code will be more testable and helps you avoid some dependency chaos. (Besides being hip and all, it is definitely a step into the right direction).
In my personal opinion having static methods is bad design in the first place. It, of course, depends on the program itself, but allowing a class to have static method will have impact on the whole design. Some reasoning behind my statement:
If static method can easily change state of some object, sooner or later bugs will emerge
If you publish static method with your program, every client that will use it will have a very strong dependency on your code. If you decide to remove or change this method someday - you will break every single client that used your class.
So, if you can - avoid it.
If, from any reason, you will insist on having static method, I guess the first solution is better. That's how singleton should work. You should obtain a reference to a SINGLETON OBJECT via static method, but this object should be then used according to all principles from Object Oriented Programming.
Currently i`m interesting in play framework because this framework promise faster development.
When i see the code, there are so many static code. even the controller declared as static function. Thus all the code that called inside static function must be static right?
My question is, is this approach is right? are there any side effect of using to many static function?
This question has been asked in a similar way previously. The simple answer is that Play uses statics where it is sensible.
The HTTP model is not an OO model. HTTP requests themselves are stateless, and therefore, static methods allow access to controllers as functional requests from client code.
The Model classes on the other hand are pure OO, and as a result are not static heavy.
Some of the utility methods, such as findAll or findById are static, but these again are not statefull, and are utility methods on the class. I would expect this in a standard OO model anyway.
Therefore, I don't think there is any risk in doing things in the way Play expects. It may look odd, because it challenges the norm, but it does so for sound reasons.
Couple of things about static methods in an object oriented language: Let me try to explain the problems if you choose to have all static methods.
Using all static functions may not be idiomatic in an Object oriented language.
You cannot override static functions in a subclass. Therefore you lose the ability to do runtime polymorphism by overriding.
The variables that you define all become class variables automatically (since all your methods are static), so essentially you do not have any state associated with the instance.
Static methods are difficult to Mock. You might need frameworks like PowerMock to do the mocking for you. So testing becomes difficult.
Design becomes a bit complex as you won't be able to create immutable classes as you really only have the class and no instance. So designing thread-safe classes becomes difficult.
To elaborate on my comment.
static methods can call non-static methods provided you have an instance of something.
class A {
public void nonStaticMethod() { }
public static void staticMethod(String text) {
// calls non-static method on text
text.length();
// calls non-static method on new Object
new Object().hashCode();
// calls non static method on a instance of A
new A().nonStaticMethod();
}
}
Yes there is a side effect of using too many static functions or variables. You should avoid unnecessary static declarations.
Because static members always creates a memory space once the class is loaded in the JRE. Even if you don't create the object of the class it will occupy the memory.
I have a helper class that creates some objects, like a builder. The helper class does not have a state. It is on a multi-threaded environment; specifically, a web server. Is this class a good candidate for being a singleton?
What would be the difference between implementing this class as a singleton and just using static methods?
What would the effect of thousands of users accessing this object/these methods be?
I could make the class a regular class, but instantiating it every time it is needed would be a waste of memory.
Infact instead of singleton you can make the methods static.
Singleton doesn't have to be only 1, you can create a pool of instances and delegate work depending on the requirement, where as you don't have such control with static methods.
discussion on Singleton vs Static methods is here
As the name suggests, singletons are used to have only one instance of the object present at the time. So singleton does have a state, but you're accessing to that one state wherever you're calling your singleton.
So if you don't need any state saved in your class/method I'd suggest to use static approach.
No need to use singleton here (since you do not need a state), you can use static methods.
Singleton in principle offers more control by allowing a state. There won't be much difference in your case, but static methods will be easier to implement and use.
What would the effect of thousands of users accessing this object/these methods be?
Again, not much difference in both cases, but in Singleton you can have a state, and if you do not implement carefully, your code will be non-thread-safe. Every user calling the static method gets its own "instance" of the method (I think this is what you ask), so no risk of running into thread-safety problems there.
As has been stated before, given that your class doesn't have object state, static methods would work just fine.
However, consider the following - Depending on the overall design of your system, you may want to be able to specify a different implementation of the methods. This is usually done with either subclassing (...), or interface implementation (now the preferred method) - look up the strategy pattern. In either case, being able to provide alternte implementations would require you to not use static methods, but to have an (empty) object to call methods on.
I have never found good answers to these simple questions about helper/utility classes:
Why would I create a singleton (stateless) instead of using static methods?
Why would an object instance be needed if an object has no state?
Often, singletons are used to introduce some kind of global state to an application. (More often than really necessary, to be honest, but that's a topic for another time.)
However, there are a few corner cases where even a stateless singleton can be useful:
You expect to extend it with state in the foreseeable future.
You need an object instance for some particular technical reason. Example: Synchonization objects for the C# lock or the Java synchronized statement.
You need inheritance, i.e., you want to be able to easily replace your singleton with another one using the same interface but a different implementation.Example: The Toolkit.getDefaultToolkit() method in Java will return a singleton whose exact type is system dependent.
You want reference equality for a sentinel value.Example: DBNull.Value in C#.
I could see a case for a stateless singleton being used instead of a static methods class, namely for Dependency Injection.
If you have a helper class of utility functions that you're using directly, it creates a hidden dependency; you have no control over who can use it, or where. Injecting that same helper class via a stateless singleton instance lets you control where and how it's being used, and replace it / mock it / etc. when you need to.
Making it a singleton instance simply ensures that you're not allocating any more objects of the type than necessary (since you only ever need one).
Actually i've found another answer not mentionned here: static methods are harder to test.
It seems most test frameworks work great for mocking instance methods but many of them no not handle in a decent way the mock of static methods.
In most programming languages classes elude a lot of the type system. While a class, with its static methods and variables is an object, it very often cannot implement an interface or extend other classes. For that reason, it cannot be used in a polymorphic manner, since it cannot be the subtype of another type. For example, if you have an interface IFooable, that is required by several method signatures of other classes, the class object StaticFoo cannot be used in place of IFooable, whereas FooSingleton.getInstance() can (assuming, FooSingleton implements IFooable).
Please note, that, as I commented on Heinzi's answer, a singleton is a pattern to control instantiation. It replaces new Class() with Class.getInstance(), which gives the author of Class more control over instances, which he can use to prevent the creation of unneccessary instances. The singleton is just a very special case of the factory pattern and should be treated as such. Common use makes it rather the special case of global registries, which often ends up bad, because global registries should not be used just willy-nilly.
If you plan to provide global helper functions, then static methods will work just fine. The class will not act as class, but rather just as a namespace. I suggest, you preserve high cohesion, or you might end up with weirdest coupling issues.
greetz
back2dos
There is a trade-off between using which one. Singletons may or may not have state and they refer to objects. If they are not keeping state and only used for global access, then static is better as these methods will be faster. But if you want to utilize objects and OOP concepts (Inheritance polymorphism), then singleton is better.
Consider an example: java.lang.Runtime is a singleton class in java. This class allows different implementations for each JVM. The implementation is single per JVM. If this class would have been static, we cannot pass different implementations based on JVM.
I found this link really helpful: http://javarevisited.blogspot.com/2013/03/difference-between-singleton-pattern-vs-static-class-java.html?
Hope it helps!!
Singleton is not stateless, it holds the global state.
Some reasons which I can think of using Singleton are:
To avoid memory leaks
To provide the same state for all modules in an application e.g database connection
For me "Want Object State use Singleton, Want Function use static method"
It depends on what you want. Whenever you want the object state (e.g. Polymorphism like Null state instead of null, or default state), singleton is the appropriate choice for you whereas the static method use when you need function (Receive inputs then return an output).
I recommend for the singleton case, it should be always the same state after it is instantiated. It should neither be clonable, nor receive any value to set into (except static configuration from the file e.g. properties file in java).
P.S. The performance between these 2 are different in milliseconds, so focus on Architecture first.
According to GoF’s book Design Patterns, chapter ‘Singleton’, class operations have the following drawbacks compared to singletons (bold emphasis mine):
More flexible than class operations. Another way to package singleton’s functionality is to use class operations (that is, static member functions in C++ or class methods in Smalltalk). But both of these language techniques make it hard to change a design to allow more than one instance of a class. Moreover, static member functions in C++ are never virtual, so subclasses can’t override them polymorphically.