Search code examples
javastaticmainclass

Is it bad programming practice to create a static singelton of main class in java?


I am considering using the Singelton Design Pattern and create a Singelton of my Main class. While I was searching, I found some comments that this is rather bad programming practice, especially since the declaration of a static method does not do justice to object-oriented programming. Do you have any suggestions for improving my code?

public class MainClass {
private static MainClass instance = new MainClass();

public static MainClass getMainInstance() {
    return instance;
}

public static void main(String[] args) {
    MainClass main = Main.instance;
}
}

Solution

  • While the use of design patterns often helps in clean programming overusing them in cases where there are not necessary will lead to overcomplicated code.

    If you want to create a singleton of your application it would be more beneficial to declare a class or better an enum that contains the application that will be run by your main function.

    Using a enum:

    public enum Application{
        instance;
    
        public void run(){
        //do awesome stuff
        }
    }
    

    This has the effect that even through serialization the application can not be duplicated but also that you can not generalize your application with interfaces.

    When using a normal class to implement a singelton you need to make the constructor private or protect the class otherwise from beeing instanciated again.

    Using a normal class with private constructor:

    public class Application{
        private static final Application instance = new Application();
    
        private Application(){}
    
        public Application getApplication(){
            return instance;
        }
    
        public void run(){
        //do awesome stuff
        }
    }
    

    This variant has the advantage that the class can still implement interfaces or extend classes e.g. Runnable. The disadvantage would be that through the use of serialization the class can still be instanciated multiple time.