Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it better to have a single instance of a class, or simply have a bunch of static methods? [closed]

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    

}
like image 267
Jaccob Avatar asked Aug 22 '13 18:08

Jaccob


People also ask

Which one is faster static method or instance method?

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.

Which one should I choose static or singleton pattern?

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.

Should singleton methods be static?

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.

Why is it not a good practice to write a lot of static methods?

Static methods are bad for testability. Since static methods belong to the class and not a particular instance, mocking them becomes difficult and dangerous.


1 Answers

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.

like image 68
Chris Jester-Young Avatar answered Sep 27 '22 18:09

Chris Jester-Young