Is getOrCreate function a good or a bad practice?
That depends on many factors. For example you might keep a local cache for some tables. Now, if you call getOrCreate(someValue) on that table, then You will have to know whether you created it or just retrieved it . Because you might need to flush and reload the cache (by making another read operation).
You might have other dependencies which might cause significant problems later on.
Though I don't completely say that this is a bad practice, I think its better to seperate your concerns.
You could do something like -
if(searchForRecord()==null)
{
addRecord();
}
Advantage of this approach : You will always know the state and behaviour of your system (what is happening).
Singleton pattern is a totally different thing. You always get ONLY ONE OBJECT
. And creation of that object is handled internally and is private to the Singleton class. You DONT need to know whether you get a new object or the old one because it doesn't matter to you
.
It's a get function. You get an instance of the class.
It doesn't matter to the outside world how the get function works internally.
public Object getObject(int key) {
Object object = getObjectFromDatabase(key);
if (object == null) {
object = createObject(key);
writeObjectToDataBase(key, object);
}
return object;
}
Every method has one function.
Edited to add: Some people look at methods from the inside out. That's what you need to do when you're writing the code for the method. I recognized that my getObject method had to do several things to truly get an Object.
However, when you're naming the method, you look at a method from the outside. Which is why my getObject method "gets an Object" (pretty short Javadoc description). If you can't write a simple declarative sentence describing the function of your method, your method is possibly too complicated.