I've been using several methods of calling methods. More recently, I've been using a static instance of a class, I do believe that's the proper term for it (please correct me if I'm wrong). Which is better (or even suggest ideas), and why?
The first way I was the simple old static methods.
static void exampleMethod1(){}
static void exampleMethod2(){}
The second way (someone said this is an improvement).
public class ExampleClass{
public static ExampleClass instance;
public ExampleClass(){
instance = this;
}
public static ExampleClass getInstance(){
return instance;
}
void exampleMethod1(){
//code
}
void exampleMethod2(){
//code
}
// To call the method I simply getInstance().exampleMethod1
}
They are faster — Static methods are slightly faster than instance methods because in instance methods, you are also working with an implicit this parameter. Eliminating that parameter gives a slight performance boost in most programming languages.
A Singleton can implement interfaces, inherit from other classes and allow inheritance. While a static class cannot inherit their instance members. So Singleton is more flexible than static classes and can maintain state.
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.
Static methods are bad for testability. Since static methods belong to the class and not a particular instance, mocking them becomes difficult and dangerous.
The term you're looking for is singleton.
Both static methods and instance methods on a singleton are okay approaches, but note that the static methods approach cannot implement an interface, so if you need to implement an interface, use a singleton.
For example:
public enum HelloWorld implements Runnable {
INSTANCE;
@Override
public void run() {
System.out.println("Hello, world!");
}
}
// ...
new Thread(HelloWorld.INSTANCE).start();
If your hello-world code were in a static method, it wouldn't have been able to directly implement the Runnable
interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With