See “Domain Driven Design” by Eric Evans.

    An entity is at the core of an application, where the part of the domain logic is implemented. It’s a small, cohesive object that expresses coherent and meaningful behaviors.

    It deals with one and only one responsibility that is pertinent to the domain of the application, without caring about details such as persistence or validations.

    This simplicity of design allows developers to focus on behaviors, or message passing if you will, which is the quintessence of Object Oriented Programming.

    Internally, an entity holds a schema of the attributes, made of their names and types. The role of a schema is to whitelist the data used during the initialization, and to enforce data integrity via coercions or exceptions.

    Automatic Schema

    When using a SQL database, this is derived automatically from the table definition.

    Imagine to have the table defined as:

    This is the corresponding entity Book.

    1. # lib/bookshelf/entities/book.rb
    2. end

    Let’s instantiate it with proper values:

    The attribute is nil because it wasn’t present when we have instantiated book.


    1. book = Book.new(unknown: "value")
    2. book.foo # => NoMethodError

    It raises a NoMethodError both for unknown and foo, because they aren’t part of the internal schema.


    It can coerce values:

    An entity tries as much as possible to coerce values according to the internal schema.


    It enforces data integrity via exceptions:

      If we use this feature, in combination with and validations, we can guarantee a strong level of data integrity for our projects.