Sobes.tech
Senior

Is a model with JSON tags (e.g., RegisterUserRequest) a domain model? How to properly separate DTO and domain entity?

sobes.tech AI

Answer from AI

A model with JSON tags, such as RegisterUserRequest, is usually a DTO (Data Transfer Object), not a domain model. A DTO is used for transferring data between layers or systems and often reflects the structure of an external API.

A domain model (domain entity) is an object that reflects business logic and rules of the subject area, often with methods and behavior.

Proper separation:

  • DTO contains only the data necessary for transfer and annotations for serialization (e.g., JSON tags in Go).
  • The domain entity contains business logic, validation, and state.

Example:

// DTO for request
 type RegisterUserRequest struct {
     Username string `json:"username"`
     Email    string `json:"email"`
     Password string `json:"password"`
 }

// Domain entity
 type User struct {
     ID       int
     Username string
     Email    string
     PasswordHash string
 }

func (u *User) ChangeEmail(newEmail string) error {
     // validation and business logic
     u.Email = newEmail
     return nil
 }

Thus, DTO and domain model have different responsibilities and should not be mixed.

Is a model with JSON tags (e.g., RegisterUserRequest)… - sobes.tech