Alvaro Pedraza Alvaro Pedraza - 7 months ago 13
Java Question

CRUD operations template in java

I'm designing a system where I must perform several CRUD operations among the System entities. Just for make sure I searched in forums to see how it's resolved by someone else.

I found 4 "patterns". All of them agree in the READ operations so I skip them. I'll define the patterns:

Pattern 1



void add(E entity);
void update(E entity);
// Read operations...
void delete(E entity);


Pattern 2



E create(<ListOfEntityProperties>);
void update(E entity);
// Read operations...
void delete(E entity);


Pattern 3



boolean add(E entity);
boolean update(E entity);
// Read operations...
boolean delete(E entity);


Pattern 4



E add(E entity);
void update(E entity);
// Read operations...
void delete(E entity);


I don't understand the difference and advantages/disadvantages of each one (and no one explains it). What are the differences between each "pattern"? What criteria to use? Can someone justify when to use one way or another (or give me another idea)?

Thanks in advance for your answers

Answer

Take Pattern 3, for example, you'd use a boolean to know if something successfully was deleted or added. The deleted case is okay, but for the added or updated case, you might want the object back with a database assigned id, which looks like pattern 4.

If you want to batch insert objects, then that's pattern 2.

And if you don't expect to return anything from a CRUD operation, then make the methods void.

The values that you want returned are the important part, the "patterns" don't matter so much, and they completely depend on the underlying API usage. For example, a SQL Server insert operation may return the row ID of the inserted object. In that case, you could return just the ID, or the same object you passed as a parameter, but with its ID field set.