Picture a simple messaging app written in Django. Users have the option to delete messages at any time, but the messages need to be retained in the database. There are two options:

  • A deleted attribute on Message. Then the call user.messages.all() would be replaced with user.messages.filter(deleted=False) everywhere in the code. This seems like it could create hidden bugs and is unintuitive.

  • Create a separate DeletedMessage object. This violates the principle of having similar data in one place, but allows for simpler method calls (i.e. user.messages.all()).

Which method is better?


You've inadvertently highlighted a code smell.

use.messages.filter(deleted=false) should only appear once in your application.

You mentioned that all the calls to user.messages.all() would need to be changed, but that's not true. Instead of having several calls to your "GetAll" function, you should wrap that in a reusable abstraction like a respository or a service.

If you don't do that, you're effectively duplicating logic and making maintenance difficult.

| improve this answer | |
  • Good point, didn't realize it was a code smell. – Jared Nielsen Mar 2 '17 at 19:03
  1. Create a new column in the message table, Deleted (bit).

  2. Create an updateable view on the message table that excludes the deleted messages.

  3. Build your data access for messages around the view.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.