Question

In a code review, I am facing a class that includes the following method pair:

getOrCreateXXXFor(YYY)
getXXXFor(YYY)

(XXX and YYY are two business logic types.) I'm not sure whether these are the ideal names.

The first is indeed related to the Singleton pattern but with a parameter and

  • returns an object, if it exists or
  • creates and returns it, if it doesn't exist.

The second one

  • returns the same object as the first method, but only, if it exists
  • throws an Exception, if it does not exist.

I'm thinking about whether they should be renamed. Do you have any better suggestions?


[EDIT] To be more specific:

  • the names should be short and concise descriptions of what happens (without the need for reading the docs)
  • the relation of the two methods should be preserved by the names

In short, it should result in a clean API. To give things a good understandable name is a central part of software craftsmanship. The topic is as little opinion based as sorting arrays.

Was it helpful?

Solution

Have a look at the Singleton-Pattern and/or the Flyweight-Pattern

I would recommend implementing it as Singleton and provide an exists method.

public class SingletonDemo {
    private static volatile SingletonDemo instance = null;

    private SingletonDemo() {       }

    public static SingletonDemo getInstance() {
            if (instance == null) {
                    synchronized (SingletonDemo .class){
                            if (instance == null) {
                                    instance = new SingletonDemo ();
                            }
                    }
            }
            return instance;
    }

    public boolean exists() {
        return instance != null;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top