DEV Community

Kaziu
Kaziu

Posted on

A Rough Guide to Entities, Value Objects, Services, and UseCases

Well, this is less about Rails and more DDD (Domain-Driven Design) and Clean Architecture territory, but hey


At a glance

Term In a nutshell Examples
Entity Something you tell apart by ID User, deal, order
Value object Something you tell apart by its contents Amount of money, phone number, address, period
Service object A box for putting procedures in Calculating tax, uploading to S3
UseCase One thing the user wants to do Registering a deal, confirming an order

Entity ─ something you tell apart by ID

A person is the same person even if they change their last name or move. On the flip side, two people with the same name and the same age are still different people.

Like this, an entity is something you tell apart by its ID (the fact that it's that one), not by its contents.

user = User.find(1)
user.update!(name: 'Suzuki') # Even if the name changes, it's still id: 1. The same user
Enter fullscreen mode Exit fullscreen mode

In Rails, most ActiveRecord models with an id are entities.


Value object ─ something you tell apart by its contents

If you swap the 1,000-yen bill in my wallet with yours, nobody cares. We don't care about the serial number; if the contents (the amount) are the same, it's the same thing. That's a value object.

PhoneNumber = Data.define(:value) do
  def initialize(value:)
    raise ArgumentError, 'Invalid phone number' unless value.match?(/\A0\d{9,10}\z/)

    super
  end

  def mobile?
    value.match?(/\A0[7-9]0\d{8}\z/)
  end
end

PhoneNumber.new(value: '09012345678') == PhoneNumber.new(value: '09012345678') # => true
Enter fullscreen mode Exit fullscreen mode

It has these three traits:

  • No ID
  • Its contents don't change (if you want to change them, you create a new one)
  • It can hold rules ("10–11 digits starting with 0," "check whether it's a mobile number," etc.)

If you keep phone numbers as plain Strings, the "check whether it's a mobile number" logic ends up copy-pasted into User, into Company, and so on. Make it a value object and all the phone number rules live in one place.


Service object ─ a box for putting procedures in

It's a class for holding procedures that would bloat a model if you put them in it, like "calculate tax" or "upload a file to S3."

class TaxCalculator
  def initialize(amount)
    @amount = amount
  end

  def call
    (@amount * 0.1).floor
  end
end
Enter fullscreen mode Exit fullscreen mode

Common conventions:

  • One job per class
  • Only one public method, like call
  • Give it a name that tells you "what it does" (avoid vague names like UserService)

Service = business logic?

Not exactly. Business rules also go into entities and value objects, and services also hold technical stuff like "upload to S3." It's more accurate to think of a service as "one of the places business logic can live."


UseCase ─ one thing the user wants to do

It's a class representing one thing the user wants to do in the app, like "register a deal" or "confirm an order." Picture the app's feature list turned directly into classes.

A UseCase is the conductor. It doesn't do the fine-grained work itself; it calls entities and services to put the steps together.

class ConfirmOrderUseCase
  def call(user:, order_id:)
    order = Order.find(order_id)
    raise 'Not authorized' unless order.user_id == user.id     # permission check

    ActiveRecord::Base.transaction do
      tax = TaxCalculator.new(order.subtotal).call                # use a service
      order.update!(tax: tax, status: :confirmed)                 # update the entity
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

Depending on the team, a UseCase might go by another name like Operation, Interactor, or Command. Different names, same role: "the procedure for one user action."


How the four fit together

UseCase "Confirm an order" (conductor)
   │
   ├─ Reads/writes entities         … Order
   │      └─ which hold value objects … amount, phone number
   │
   └─ Calls services                … tax calculation, sending email, S3
Enter fullscreen mode Exit fullscreen mode
  • The UseCase decides the game plan
  • Within it, it manipulates entities and hands work off to services
  • Value objects are used as "values" inside entities and services

Calls go one way, top to bottom. A service never calls a UseCase.

Top comments (0)