Separation of business logic and model

I have this question that bothered me for a while. At first glance, this may seem like a fairly simple question, but there seems to be no clear answer. My basis for asking this question is a Python project that uses PostgreSQL through SQLAlchemy, but the specific language and tools used do not really matter.

The main question is where to put the logic when using ORM? More specifically, what logic should go into the methods of my matching classes?

It seems that there are some clear cases, for example, a basic check of properties, such as the minimum length, or whether or not the email address should belong to the ORM layer (or even the database itself).

A simple concrete example is fine, so let's say we save User objects, users have an email address (which is their unique identifier), a password, and an activation identifier. When an account is created, an activation identifier is assigned and sent to the user, which is then used to set a password.

Look at a few scenarios:

  • The user creates an account;
  • The user activates the account (i.e. sets a password).

Therefore, when a user creates an account, we need to perform some basic check: * Email address correctly => ORM; * Unique email address => ORM or database (unique restriction); * Set random activation id => ORM

When a user activates his account, I encounter problems. I would like to check the password provided by you (for example, is it enough enough?), But the model should store the password using some kind of hashing or encryption algorithm. There seem to be two options:

1: check the activation identifier and password validity outside the model, the hash password, then set the User.password parameter to the hash value and the User.activation identifier to null (to signal the active account).

2: Create a method User.activate (activ_id, password), which checks each value and sets the corresponding properties User.password and User.activation_id.

3: Hybrid option, execute option 1, but do you have any hook or event setting activation_id = null when the password is set (if we assume that either the activation ID or password can be set, then this hook satisfies the basic consistency property of the model).

I searched on the Internet, and there are some sources that talk about this problem (including some SO questions), but no one answers the question.

+6
source share

Source: https://habr.com/ru/post/955603/


All Articles