Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - updateOrCreate method, isnt it programming principles breaking

I found in Laravel - Eloquent's method like updateOrCreate(). Why in framework we can find methods which are breaking clean code and SOLID rules?

like image 690
JakiLim Avatar asked Jun 16 '21 17:06

JakiLim


2 Answers

I think you're referring to the Single Responsibility Principle as stated in SOLID. Long story short, yes, some methods in Laravel PHP framework breaks SOLID, and not just in the Eloquent ORM.

This is called an Anti-Pattern, as stated in Wikipedia:

An anti-pattern is a common response to a recurring problem that is usually ineffective and risks being highly counterproductive.

The reason we use this "anti-pattern" is just for the sake of simplicity and productivity. Depends on your application, handling data with ORM (such as Eloquent) sometimes can be complex, and this is why anti-pattern come to rescue.

With eloquent, you can use create() to just add a new record and updateOrCreate() to add a new record or update it if it already exists.

like image 184
Ezra Lazuardy Avatar answered Oct 18 '22 19:10

Ezra Lazuardy


There's no violation of any principles here and it's not an anti-pattern either, which by definition would be a code smell.

I'm not sure about the specific implementation we are talking about here, but generally speaking an "update or create" operation must be atomic and that would just be cumbersome to implement with distinct create, exists & update operations.

For instance, imagine the client had to write the following code every time he wants to do an "update or create".

if (!exists()) { // this check could be stale without proper locking
   create();
} else {
   update(); // record could have been deleted already
}

As we can see not only that's a lot of ceremony, but proper locking/retry would need to be used to make sure that the record has not been inserted right after we did the exists() check or inversely deleted right before we update().

"update or create" is conceptually a single "merge" operation which cannot be implemented effectively with the client with a bunch of seperate methods. Should they have called it merge you wouldn't have asked this question ;)

It's not because there's an "or", "and", "ifNeeded" or whatever in a method name that it necessarily has too much responsibility. It's a strong indicator it may be the case, but use your own judgement and do not follow principles blindly.

like image 26
plalx Avatar answered Oct 18 '22 19:10

plalx