Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is getOrCreate function a good or a bad practice?

In my code (hypothetical) I'd like to use getOrCreate function. I pass the parameters and I either get a new entity or I get an existing entity from the database, if such entity exists.

From one point of view this is a wrong approach, because function should not do more than one thing. But from another point of view this is a single operation, that just does not have a proper word in English and I can reduce some duplicities in the code.

So is using this approach a good or a bad practice? And why?

like image 894
Michal Krasny Avatar asked Jun 03 '14 08:06

Michal Krasny


1 Answers

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.

like image 173
Gilbert Le Blanc Avatar answered Sep 23 '22 03:09

Gilbert Le Blanc