Access singleton's fields via a static method - java

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.

Related

static or instance methods for dbHelper?

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.

Which is the best way to do the following task in java

I have more than 20 commonly used methods in my application. I would like to move that 20 methods into a common class.
Here my doubt is, define all the methods are static or normal method and create a global object to access that normal methods.
class Common {
public String method1() {........}
public String method2() {........}
public String method3() {........}
public String method4() {........}
public String method5() {........}
...
}
Creating object.
class CommonService {
private static Common common;
public static Common getCommon() {
if(null == common) {
common = new common();
}
return common;
}
}
If we create all the methods using static means, all 20 methods are stored in PermGen section of the heap.
But if we follow above method means, only one object can be created and stored in java heap.
Please clarify which one is the best way.
If we create all the methods using static means, all 20 methods are stored in PermGen section of the heap.
Methods are not data, but code. Where code is stored does not depend on whether a method accepts an implicit this parameter or not. If you use the singleton approach, method code will still occupy storage and additionally there will be an instance on the heap.
However, all of the above is irrelevant and you are focusing on a completely wrong aspect of your design. What matters is how the decision will affect the code which uses these methods:
static methods are simple and a great choice for pure functions (which don't depend on any external state);
singletons allow polymorphism, therefore make the methods easier to mock for testing.
You should think about the "best" way in terms of design.
If the methods are used for general purposes, making them static is preferable, as you won't have any state to store and you'll save memory this way.
You should consider other things before deciding if you want to use static methods in your utility class or not. On one hand the utility class will be very easy to test, and it's highly accessible. On the other hand, it's very hard to mock static methods in your test.
If I have a utility class, I would write it as follows:
public final class Common {
private Common() { }
public static int method1() { }
public static int method2() { }
// ...
}
"Common functions" is not quite accurate. It really depends on what you want to do, for example when I make some string utils I make StringUtils class and it has what I need. Whether to make it static or not depends on data to be processed, if one information might be used more than once for a call then answer is simple - use instances.
That depends on what the methods do.
If those methods are just helper methods, that do not alter state then static is probably better because that way you do not have to create an object every time you want to use one of the methods. You can just call Common.method()
However, if the object has state then you should rater use object methods and create a new object when you want to use the methods.
Hope this helps.
If sense of this method is "execute pure function" like mathematical sin(x), cos(x) etc static method is the best.
They belongs to one domain? (range of themats) or to different? (then create more "utility classes" with correct name)
If have state (like many people say) maybe better is singleton.
Shape of the question "i have 20 method in application" and name Common suggest previous (older) design problem, I say "procedural thinking", poor vision of OOP.
Hard to say without code.

Benefit of getting an instance in Java

I've seen this code which has two different way its written
public static void main(String[] args) {
Tester.boot();
new tester();
Tester class:
public static tester instance;
public static void boot() {
if (instance == null)
instance = new tester();
}
public Tester() {
System.out.println("test made");
}
What is the difference beetween tester.boot(); and new tester();
Are there any benefits to either?
There are three concepts being displayed here:
Lazy Initialization
Static
Encapsulation (at least the lack thereof)
Tester class:
if (instance == null)
instance = new tester();
That's used when you wish to control the construction of an object. The variable instance controls if new Tester() will be called by boot().
This can be used to implement Lazy Initialization. That's the practice of delaying construction of an object until it is needed. It's typically used when construction is both expensive and not always needed. Here it is delayed until boot() is called. Lazy Initialization is not only used for singletons. Some believe that using Lazy Initialization in java to create a singleton is actually wrong because of how the class loader works. They claim it's a habit ported over from c++ where it made sense. As a pattern, singleton has been controversial enough that some call it an anti pattern.
Tester class:
public static tester instance;
boot(), constructs a Tester object, sets instance to that object (Note: tester should have been capitalized). The fact that instance, which is of type Tester, resides in theTesterclass means thatTesteris [**self referential**][7], like the nodes in a linked list. But, unlike nodes, becauseinstanceisstatic, allTesterobjects have the same copy ofinstance`.
Because boot never puts what it constructs anywhere but in instance, only one boot() constructed Tester object ever exists at any one time, so long as instance is never copied anywhere. It easily could be, because it's public.
So long as instance is never set back to null boot() will construct a Tester only once no matter how many times it's called. Since instance is public it could be set to null at any time by anything that knows about Tester. Doing so would allow boot() to construct again and the old Tester object would be forgotten (garbage collected).
Since Testers constructors have not been made private there is no guaranty that Tester is never constructed by something other than boot(). That means there could still be many Tester objects running around. But they all have one instance in them that may or may not be themselves.
A classic singleton would have Lazy Initialization, be self referential, and be encapsulated in such a way that at most only one Tester object would ever exist. However, There is nothing here that proves this was meant to be a singleton in the first place. This could be a construction optimization gone horribly wrong.
This is sort of implementation of a SINGLETON pattern, in Java.
Look here to understand the concepts behind this pattern click here.
Shortly, you want to use this pattern if you want to have an instance of the class Instance trough all application's life cycle.
To understand it, the key in your code is in the part "if(instance == null)" {instance should be written with lower key, as it should be a class variable}.
If you go simply with the "new ..." any nuber of instances of this variables could be created.
If instead you use the boot method, you are sure that the instance is always the same.
Anyway in the implementation you have written something is missing.
You should refer to this link, where there is also a complete implementation in Java programming language.
boot is useless, you're not showing how Instance is used. But I think it's there to implement a singleton, meaning to assure that only one instance of the class is created. I don't think it's a good implementation as Instance can be used by mistake without being initialized.
When you write new tester() then you're creating a new instance of tester object.
Please follow Java Naming Convention and rename your variables accordingly.
read this comment to know when it makes sense to have an instance and when not.
To be specific--if you use tester.boot() it would set "instance" properly, if you call the constructor directly, it will not.
This is a really broken version of the singleton pattern, to do it correctly the constructor should be made private which makes new Tester() impossible.
Also, the boot method should look a little more like:
public synchronized static Tester boot()
{
if(instance == null) {
instance=new Tester();
}
return instance;
}
and even that is probably iffy.

Are there any side effect of using to many static function?

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.

Writing to a static variable in an instance method, why is this a bad practice?

I am a little confused here with this findbugs warning in eclipse.
public class MyClass {
public static String myString;
}
public class AnotherClass {
public void doSomething() {
MyClass.myString = "something";
}
}
This gives me a findbugs warning "write to static field from instance method", however this does not give me a warning:
public class MyClass {
public static String myString;
}
public class AnotherClass {
public void doSomething() {
doAnotherThing();
}
public static doAnotherThing() {
MyClass.myString = "something";
}
}
How is this any different?, and why is writing to a static variable from an instance method a bad practice?, I assume it has to do with synchronization, but it is still not clear to me.
I know this looks like the variable should be final, but I am loading the value from a properties file.
Its a form of aliasing, which may be counter-intuitive. Counter-intuitive code hampers ease of maintenance.
Logically, we expect instance methods to affect that instance's data. We expect static methods to affect static data.
Let's rename doSomething to initialize:
...
a.initialize();
...
b.initialize();
...
The reader of this code may not immediately realize that the instances of a and b are actually affecting the same data. This may be a bug since we're initializing the same memory twice, but its non-obvious since it seems reasonable that we may need to call initialize on each instance.
However, the the code were:
...
MyClass.initialize();
...
MyClass.initialize();
...
In this case, its more intuitive that we're likely affecting the same static data and this is likely a bug.
This is similar to the common version of aliasing where two variables in the same scope point to the same instance.
For your last example,
an instance calls a static method
The fact that an instance method is calling a static method isn't expected to raise flags. The examples were this is useful far outweigh where its likely a problem.
a static method of one class affects another class' static data
In one sense, it should generate a different, but similar warning: that one class is messing with the data of another class. However, by making the static variable public is a way of tacitly approving of this, so such a warning isn't necessary.
Keep in mind that FindBugs is simply trying to flag potential likely problems, not every possible problem, in your code. Your first example is likely a potential maintenance issue that you need to examine whether its a real problem. Your second example is likely not a problem or it is a real problem that is too similar to use cases where it is not a problem.
There aren't many use cases for why you would want to change a static field.
Remember that if you set this field to a new value that this value has changed for all instances of this class.
This might get you into trouble in a multi-threaded environment, where more than one thread is calling doSomething(). Proper synchronisation is required.
In 99% of all cases, you want your instance methods to change the non-static fields only, which is why findbugs warns you.
And findbugs isn't clever enough to find out about your instance method indirectly changing the field in your second example :)
This is what FindBugs has to say about this: http://findbugs.sourceforge.net/bugDescriptions.html#ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD
This is my take, so take it with a grain of salt. You mentioned synchronization issues, which are a major reason for this warning, but more importantly, the two cases are fundamentally operating on different conceptual "levels" of data. Instance methods are "owned" by objects and modify data that describes individual instances. Class methods are generic operations and state that, while related to the class, are not related to individual objects. Thus, modifying that state from within each instance would probably (but not necessarily) be a poor design decision.
Because changing a static field changes it for all instances, causing untold problems if not properly synchronised.
If you're reading in a properties file to set shared fields, then do it in a static method. Alternatively, refactor the fields into a separate singleton instance that the other class can only read from. If you're only going to have one instance, then use a singleton pattern and make the fields non-static.
Static methods should only affect static data, and instance methods should only affect instance data.
I don't think synchronization (mentioned in several answers) has any bearing on this. After all, static methods can be called from multiple threads just as easily as can instance methods.
The reason for the warning (not very well explained by the FindBugs documentation) is, I think, hinted at by a couple of answers: it's suspicious and possibly a mistake. Like Jochen Bedersdorfer said, there aren't all that many use cases where you want to assign to a static variable in one class from an instance method in another. Just like
while (x = y) {
// ...
}
isn't technically an error (and actually legal Java if x and y are boolean), it's almost always a mistake. Similarly, the authors of FindBug felt the same about the subject case.

Categories