vendredi 30 décembre 2022

Alternative to multiple instances of pseudo-singleton

I stumbled upon a pseudo-singleton class that is responsible for housing a few collections. It looks something like this:

public class PseudoSingleton {
    private List<Object> collection1;
    private List<Object> collection2;
    private static PseudoSingleton instance = null;

    public static synchronized PseudoSingleton getInstance() {
        if (instance == null) {
            instance = new PseudoSingleton();
        }
        return instance;
    }

    public static synchronized void reload()  {
        instance = new PseudoSingleton();
    }

    private PseudoSingleton() {
        load();
    }
    
    private void load() {
        //parse some files from disk and fill collections
    }
}

The reason it is coded like this is that in a few places in code a comparison of collection1 before and after reload needs to be done.

However this way seems like a major code smell to me.

I tried to refactor the code slightly by making the reload() method not static:

public synchronized void reload() {
   //clear collections
   //load collections
}

In order to be able to compare collection before reload I added a method that needs to be called before reloading the collection:

public List<IfCluType> getCluInterfacesCopy() {
   return new LinkedList<>(clus);
}

However, in review I got a comment that the previous way was better and I should leave it as is. I am not convinced. Should I insist to go my way or leave it? Or is there a better way to code it?

Aucun commentaire:

Enregistrer un commentaire