mardi 26 juillet 2022

Best practice when creating a "draft version" of an entity

I'm not sure if there's an answer to this question somewhere but I wasn't able to find the right keywords to look for something like this. If I've missed something, please point me in the right direction.

This is a general design question. I have an entity with a lot of fields (linked with an ORM and database - Doctrine, Hibernate whatever). Naturally, I put "not-nullable" constraints wherever needed.

For the sake of understanding let's take the example of a job offer entity called Offer. So the fields will be title, description, domain, typeOfOffer, companyName, experience, location etc. None of the fields can be null in this case.

Now a new requirement was that there a draft version of the offer can be saved to the database. Which means, all the fields can be null and edited later before a final submit.

Now I can think of two ways to do this.

  1. Create a draft version of the entity with the exact same fields and make it all nullable. When finally the draft is submitted, create the actual entity and delete the draft. While this seems easy and straightforward, it's a lot of code duplication so it does not sit well with me (even if I create a base class and inherit, it doesn't reduce code unless, I'm missing something).

  2. Make all the fields nullable to boot and then handle validation in the code (and not leave it to the ORM) based on a field that stores the status of the entity (like OfferStatus [draft, final] in this example). I'm not sure if this is the right way as I feel like constraints need to be the job of the database.

If you think there's a better design pattern or way to implement this, please let me know.

Aucun commentaire:

Enregistrer un commentaire