javaoopmethod-names

Looking for better method names


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

The second one

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


[EDIT] To be more specific:

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.


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;
        }
    }