Chapter 5: Entities

Ace your homework & exams now with Quizwiz!

Doing a lot of entity-relationship (ER) modeling in Java code puts too much focus on database, tables, and columns, and how those are reflected in objects. That can lead to a largely ________, composed of a lot of getters and setters.

Anemic Data Model

When deciding to have the __________ generate unique identity for your Entities, UUID is a relatively fast identity to generate, requiring no interaction with the outside, such as a persistence mechanism. For higher-performance domains, we can cache any number of UUID instances, refilling the cache in the background. If cached UUID instances are lost due to server restart, there are no gaps in identities because they are all based on random, manufactured values.

Application

Having another ________ assign identity is the most complex of identity creation strategies for Entities. The maintenance of the local Entity is dependent not only on transactions caused by local domain behaviors but possibly also on those that occur in one or more external systems. Use this approach as conservatively as possible.

Bounded Context

When __________ makes sense, languages and frameworks such as Groovy and Grails, Ruby on Rails, and the like make the most sense. If the choice is correct, it should save time and money. On the other hand, if we apply this technique to the wrong system -- more complex ones that deserve the precision of DDD - we may regret it.

CRUD

Don't put too much responsibility on a single Entity. Importantly. For example, consider the example from the Book. The Person Entity is modeled as a separate class to avoid placing too much responsibility on the User: - Person: Contains and manages personal data about a User, including name and contact information. Is the Person an Entity or a Value Object? Again here the word ________ is key. The team made it an Entity. Another question: should clients be given access to the Person object inside the User? If clients were given access to the shape of User, with navigation into the Person in order to execute behavior, that could require client refactoring later (e.g., in case User is not always a Person, but maybe a System). Further, the accessor could later be redesigned to serve a Principal interface, and Person and System would each be specialized Principal. The team would be able to refactor this as they gained deeper understanding .

Change

In an early form, your Ubiquitous Language can take the shape of a glossary and a set of simple usage scenarios. Yet, it would be a further mistake to think of the Language as the glossary and scenarios only. In the end, the Language is modeled by your ________, and it may be difficult or impossible to keep documentation in sync.

Code

Some developers refer to the precondition checks in setters (such as checking if the value is null, or empty strings, or checking if an e-mail matches a regex) as ________.

Defensive programming

A useful approach to validation for whole objects is ________. Ward Cunningham says that this is "a class of checking that should be deferred until the last possible moment." It is deferred because it is a kind of very detailed validation, one that we would run over at least on complex object, or even a composition of objects. This approach is also an approach to address larger compositions of objects.

Deferred Validation

A ________ approach to assertions in setters enables us to specify the preconditions, postconditions, and invariants of the components we design. This approach is used for validating attributes/properties of an Entity.

Design-by-contract

When validating object compositions (a composition of Entities), decide whether validation is appropriate at all times. On occasion an Aggregate or a set of Aggregates is in a temporary, intermediate state. Perhaps, we could model a status on a Aggregate to indicate this, preventing validation at inappropriate times. When the conditions are ripe for validation, the model could inform clients by publishing a __________. When received by the client, it indicates that validation is now appropriate. Until that time, the client refrains from validating.

Domain Event

There is a tendency for developers to focus on data rather than the domain. Instead of designing domain concepts with rich behaviors, we might think primarily about the attributes (columns) and associations (foreign keys) of the data. Doing so reflects the data model into object counterparts, which leads to almost every concept in our "__________" being coded as an Entity abounding with getter and setter methods. Although there may be nothing wrong with property accessors, that's not the only behavior DDD Entities should have.

Domain Model

To validate object (Entity) compositions, we can use Deferred Validation -- waiting until the last moment to validate -- for the more complex actions requiring all of the checks of simpler activities and then some. Here we determine not only that an individual Entity is valid, but that a cluster or composition of Entities are all valid together, including one or more Aggregate instances. It may be best to manage that kind of validation using a __________, which can use Repositories to read the Aggregate instances it needs to validate. It can then run each instance through its paces, separately or in combination with others.

Domain Service

When considering the requirement: - Users of a system must be authenticated but can be authenticated only if the tenant is active. Since there is more to authentication then merely finding a User Entity that matches a specific username and password, a higher-level coordinator is needed. ________ are good at that. For example, the team captures the authenticationService by name and added it to the Ubiquitous Language.

Domain Services

Side effects can occur when we use relational databases for object persistence, which leak into our __________.

Domain model

Another problem that can occur when identity generation is delayed until the Entity is persisted (i.e., late identity generation) occurs when two or more new Entities must be added to a java.util.Set, but their identify has not yet been assigned making them equal to the other new ones. To avoid this bug, we must either change the design to allocate and assign identity ________, or we refactor the equals() method to compare attributes other than the domain identity. If choosing the equals() method approach, it must be implemented as if the Entity is a Value Object. Overall, it is preferred to use latter approach rather than changing equals() and hashCode().

Early

Identity generation can occur ________, as part of the object's construction.

Early

When ________ identity generation is used, a correctly designed constructor takes as a parameter at least the unique identity of the Entity. If the Entity is queried by other means, such as with a name or description, we would also include all such as constructor parameters.

Early

When using ________ identity generation, the unique identity is queried from the Repository and assigned during instantiation of the Entity (i.e., new Product()). The complexities of identity generation are hidden behind the Repository implementation.

Early

________ identity generation and assignment happen before the Entity is persisted.

Early

After an ________ is discovered and named, uncover the attributes/properties that uniquely identify it and enable it to be found.

Entity

After essential attributes of your ________ are identified, the team could look into indispensable behavior. When deciding which operations to add to your Entity, consider how the domain experts talk about the Entity and your Ubiquitous Language, instead of providing setters and getters for specific attributes. Importantly, include essential behaviors in the glossary of your Ubiquitous Language. For instance, consider the example from the book. The Tenant Entity has a requirement that it can be active or inactive. The team could have decided in favor of declaring method setActive(boolean), though that wouldn't really address the terminology of the requirement. It's not that public setter methods are never appropriate, but they should be used only when the Language allows for them and usually only when you won't have to use multiple setters to fulfill a single request. The multiple setters make the intention ambiguous. They also complicate publishing a single, meaningful Domain Event as an outcome of what should actually be a single local command. To address the Language, the team noted that domain experts talk about activating and deactivating. To incorporate that terminology they'd assign operations such as activate() and deactivate() instead.

Entity

In the early stages of designing an __________, we purposely focus only on those primary attributes and behaviors that are central to its unique identity, as well as those useful for querying it, and we purposely ignore all other attributes and behaviors until we settle on the primary ones.

Entity

There are times when an __________ is not the appropriate modeling tool to reach for. Misappropriated use happens far more often than many are aware. Often a concept should be modeled as a Value Object. If this is a disagreeable notion, it might be that DDD doesn't fit your business needs. It is quite possible that a CRUD-based system would be more fitting.

Entity

We design a domain concept as an __________ when we care about its individuality, when distinguishing it from all other objects in a system is a mandatory constraint. An component is a unique thing and is capable of being changed continuously over a long period of time. Changes may be so extensive that the object might seem much different from what it once was. Yet, it is the same object by identity.

Entity

When an object is distinguished by identity, rather than its attributes, make this primary to its definition in the model. Keep the class definition simple and focused on life cycle continuity and identity. Define a means of distinguishing each object regardless of its form or history. The model must define what it means to be the same thing. This object is known as an __________.

Entity

When another Bounded Context assigns identity of an ________ in our Bounded Context, we need to integrate to find, match, and assign each identity. Making an exact match is the most desirable. Users need to provide one or more attributes, such as an account number, username, e-mail address, or other unique symbol, to pinpoint the intended result.

Entity

By the definition of Entity, it is not necessary to track the changes that occur on state over its lifetime. However, sometimes domain experts care about important occurrences in the model as time passes. When that's the case, tracking specific changes to Entities can help. The most practical way to achieve accurate and useful change tracking is with Domain Events and an __________. We create a unique Event type for every important state-altering command executed against every Aggregate that domain experts care about. The Events are published as the command methods complete. A subscriber registers to receive every Event produced by the model. When received, the subscriber saves the Event to the store.

Event Store

Publishing Domain ________ when modification of an Entity would enable change tracking through the life cycle of all objects and would enable outside subscribers to synchronize with the changes, giving outsiders the potential for autonomy.

Events

The Ubiquitous Language of a Bounded Context must be developed through careful discussion with domain ________ and by mining requirements. Some terminology uncovered will be nouns that name things, adjectives that describe them, and verbs that indicate what the things do. It would be a mistake to think that the objects distill to only a set of nouns that name classes and verbs that name prominent operations, that we can capture deep insight by considering nothing else.

Experts

Use a ________ for complex Entity instantiation.

Factory

For Entities, surrogate database primary keys can be used throughout the data model as ________ in other tables, providing referential integrity. This may be a requirement for data management in your enterprise. This also supports table joins to optimize queries when reading Aggregates out of the database.

Foreign Keys

The Entity serving as an Aggregate Root requires ________ unique identity.

Global(ly)

The constructor delegates instance variable assignment to its own internal attribute/property setters, which provides self-encapsulation for the variables. The self-encapsulation enables each setter to determine the appropriate contractual conditions for setting a portion of the state. Each of the setters individually asserts a non-null constraint on behalf of the Entity, which enforces the instance contract. The assertions are called ________.

Guards

An Entity's unique identity may or may not also be practical for finding or matching. Using the unique identity for matching usually depends on how __________ it is. For example, a person's name or a tax ID.

Human-readable

Rather than focusing on the attributes or even the behavior, strip the Entity object's definition down to the most intrinsic characteristics, particularly those that __________ it or are commonly used to find or match it. Add only behavior that is essential to the concept and attributes that are required by that behavior.

Identify

Some common __________ creation strategies for Entities include: 1. Provided by User 2. Generating by Application (UUID library) 3. Generated by Persistence Mechanism 4. Assigned by another Bounded Context

Identity

In most cases, the unique identity of an Entity must be protected from modification, remaining stable throughout the lifetime of the Entity to which it is assigned. In other words, the identity must be ________. This can be done trivially, typically through creating guards in setters to prevent even the Entity itself from changing the state of the identity if it already exists.

Immutable

An aspect of DDD modeling is to discover the roles and responsibilities of objects. In object-oriented programming, generally ________ determine the roles of an implementing class. When designed correctly, a class has one role for each interface that it implements. If the class has no explicitly declared roles -- it doesn't implement any explicit interfaces -- by default it has the role of its class. That is, the class has the implicit interface of its public methods. For example, the class User from the examples in our book implements no explicit interfaces, yet it plays one role, a User.

Interfaces

When modeling the domain, we can leverage ________ to hide implementation details that we don't want leaking out of the model to clients. Design this to expose exactly what we want to allow clients to use, and nothing more. The implementation class can be far more complex than that. Importantly, ensure that the Ubiquitous Language holds sway over any technical preferences. With DDD, it's a model of the business domain that matters most.

Interfaces

Sometimes an Entity maintains one or more ________, which is a state that must stay transactionally consistent throughout the Entity life cycle. If an Entity has an one of these that is satisfied by the non-null state of a contained object, or calculated using some other state, that state must be provided by one or more constructor parameters.

Invariants

Consider that we can tolerate the ________ allocation of identity when a new Entity is persisted. Consider a scenario where the client subscribes to outgoing Domain Events. An Event occurs when a new Product instantiation completes (i.e., new Product()). The Domain Event is received before the client has the opportunity to add the new Product to the ProductRepository (i.e., to persistence). In this case, the Domain Event would not contain the valid identity of the new Product, meaning that listeners won't know how to identify the object. For the Domain Event to be correctly initialized, the identity generation must be completed early.

Late

Identity generation can occur ________, as part of the object's persistence.

Late

One possible downside of using a persistence mechanism to generate unique IDs your Entities is performance. One way around this is to cache sequence/increment values in the application, such as in a Repository. This can work well, but we generally count on losing a good number of unused values when server nodes must be restarted. If the gap caused by lost cache are unacceptable, caching preallocated values may not be a practical or necessary option. It may be possible to harvest and recover lost identities, but that may be more trouble than it is worth. Preallocation and caching are not an issue if the model can suffice with ________ identity generation.

Late

The simplest way to allocate a unique identity for an Entity is to have the data store generate it the first time the object is persisted (i.e., the ________ allocation).

Late

________ identity generation and assignment happen when the Entity is persisted.

Late

How do clients ensure that Entity validation occurs? And where does validation processing begin? One way places a validate() method on all Entities that require validation and may do so using a _________, which is typically an abstract class (also used to hide surrogate identities/attributes). Any subclass can safely have its validate() method invoked. However, this doesn't mean that the Entity itself performs validation. Yet, it does allow the Entity to determine what validates it, relieving clients from that concern. (The client may pass in a notification handler tho). Moreover, the Entity needs to know nothing about how it is validated, only that it can be validated.

Layer Supertype

When needed, it's best to hide the surrogate identity of an Entity from the outside world. Because the surrogate is not part of the domain model, visibility constitutes persistence leakage. Although some leakage may be unavoidable, we can take some steps to tuck it away from model developers and clients. One safeguard employs a ________. This can be enforced by an abstract base class for Entities that hides the surrogate primary key from the view of clients using protected accessor methods.

Layer Supertype

________ may add value other than hiding a surrogate identity, such as for supporting optimistic concurrency, as seen in Aggregates.

Layer Supertypes

________ Identity means that Entities held inside an Aggregate need only have uniqueness among other Entities held inside the same Aggregate.

Local

When deciding to have the application generate unique identities for your Entities, depending on the level of trust you have in the uniqueness of individual segments of the hexadecimal text UUID, you may decide to use just one or a few segments of the whole. The shortened identities are more trustworthy when used only as the __________ of Entities within the Aggregate boundary.

Local Identity

It might help domain ________ to make role interfaces finer grained. For example, an Entity may implement one or more fine-grained role interfaces. Each defines only a single operation. Some advantages to this style include that the role of an Entity can change from use case to use case. When a client needs to add a new Order instance to a Customer Entity, the role is different from what they want to make the Customer preferred. There's also a technical advantage. Different use cases may require specialized fetching strategies. Role marker interfaces lend a hand to enabling behind-the-scenes hooks. Other use-case-specific behaviors can be associated with any given role, such as validation, enabling the execution of a specific validator as the Entity modifications are being persisted.

Modeling

For validating an entire Entity object, you should design a separate class that is responsible for validation. When designing a separate validation class with Java, place it in the same ________ (package) as the Entity. Declare attribute/property read accessors with at least protected/package scope.

Module

For validating an entire Entity object, you should design a separate class that is responsible for validation. This validation class should also delegate to a separate class that is responsible for __________ handling. This has the advantage of not coupling error messages, or message property keys, or anything specific to notification, to the validation process.

Notification

One possible downside of using a ________ mechanism to generate unique identities for your Entities is performance. It can take significantly longer to go to the database to get each value than to generate identities in the application. Much depends on database load and application demand.

Persistence

When deciding to have the Application generate unique identities for your Entities, with such a large identity, the use of UUIDs could in rare cases be rendered impractical because of the memory overhead. In such cases, an 8-byte long identity generated by the __________ mechanism would improve matters. A smaller, 4-byte integer, with two billion or so unique values, may even suffice.

Persistence

When having the application generate unique identities for your Entities, for Aggregate Root identity generation, the ________ should serve as a Factory for your application-generated identities. (E.g., return a ProductId for a Product).

Repository

When uncovering ________, you need to be careful because you don't want to get down into the technical and tactical modeling weeds. For instance, following the example from the book, the team originally identified that they didn't want to associate the Entities Tenants to Users by requiring that the former collects and contains the latter. Instead, they can clarify this as "Tenants allow for the registration of many users by invitation." They found that the original statement about users under tenancy control was incomplete. The fact is that users are registered within a tenancy, and by invitation only.

Requirements

Embedding validation inside an Entity gives it too many ________. It already has to address domain behavior as it maintains its state. Instead you should design a separate validation class for validating the entire object.

Responsibilites

The problem of object ________ describes an object with multiple personalities, which is not medically the definition of this term. The actual problem behind the confusing name is object identity confusion.

Schizophrenia

To protect (validate) a single attribute or property from being set to an invalid value, we can use ________, which is "designing your classes so that all access to data, even from within the same class, goes through accessor methods." This allows fro the abstraction of an object's instance (and class/static) variables. It provides a way to easily derive attributes/properties from any umber of others the object holds. It also lends support for a simple form of validation using assertions that follow a design-by-contract approach.

Self-encapsulation

For validating an entire Entity object, you should design a separate class that is responsible for validation. The validation class can implement the ________ pattern or the Strategy pattern. If it detects an invalid state, it informs the client or otherwise makes a record of the results that can be reviewed later (for example, after batch processing). It is important for the validation process to collect a full set of results rather than throw an exception at the first sign of trouble.

Specification

To validate a whole Entity, we need to have access to the state of the entire object -- all of its attributes/properties. We also need a Specification [Evans & Fowler, Spec] or ________ [Gama et al.] for the validation.

Strategy

Some ORM tools, such as Hibernate, want to deal with object identity on their own terms. Hibernate prefers the database's native type, such as a numeric sequence, as the primary identity of each Entity. If the domain requires another kind of identity, it causes an undesirable conflict for Hibernate. To cure this, we need to use two identities. One of the identities is designed for the domain model and adheres to the requirements of the domain. The other is for Hibernate and is known as a ________ identity.

Surrogate

When another Bounded Context assigns identity of an Entity in our Bounded Context, this has ________ implications. If externally referenced objects transition in ways that affect local Entities, the problem can be solved using an Event Driven Architecture with Domain Events. Our local Bounded Context subscribes to Domain Events published by external systems. When a relevant notification is received, our local system transitions its own Aggregate Entities to reflect the state of those in external systems. Sometimes changes within the local Bounded Context need to be pushed to the originating external system. This technique leads to more autonomous systems. When autonomy is achieved, it can actually narrow searches to local objects. This is not a matter of caching foreign objects locally. Rather, it involves translating foreign concepts into those of the local Bounded Context.

Synchronization

When applying DDD ________ design, only model requirements that are clear to your team. You can postpone more complex modeling for later iterations of design. For instance, the team from the book was faced with this requirement: - Tenants allow for the registration of many users by invitation. They understood this requirement to be a bit more complex than they wanted to deal with in the first, rapid iteration. The requirement didn't tell them enough to be understood clearly. For example, there seems to be some kind of Invitation object involved, but the behavior to manage invitations wasn't clear either. So the team postponed modeling this until they could solicit more input from early domain experts and early customers.

Tactical

The ________ in a cleanly separated Bounded Context gives us the concepts and terms we need to design our domain model.

Ubiquitous Language

If you have a bunch of things, and one the things needs to be found out of many, you need ________ to distinguish the one from all others. A search will need to resolve from many users in association with a tenant down to a single one. This plus a need for mutability is a sign that those things should be modeled as an Entity.

Unique identity

It appears to be a straightforward approach to have a user manually enter the details of __________ of an Entity object. True, it is a simple enough approach. But there can be complications. One complication is relying on users to produce quality identities. The identity may be unique but incorrect. Most times identities must be immutable, so users shouldn't change them. This is not always the case, and there may be advantages to enabling users to correct identity values. An example: if we use the titles of Forum and Discussion as unique identities, what would happen if the user spelled the title incorrectly, or later decided that the title was not as fitting as it could have been? What's the cost of change? Preventing this problem starts with design discussions. Teams need to consider fail-proof approaches to enable users to define unique identity. Workflow-based identity approval is not conducive to high-throughput domains but works best when human-readable identity is a must. If it takes extra time and effort to create and approve an identity that will be used pervasively throughout the business for years to come, and supporting a workflow is possible, adding a few extra cycles to ensure the quality of the identity is a good investment.

Unique identity

When deciding to have the application generate identity for your Entities, there are highly reliable ways to autogenerate unique identities, although care must be taken when the application is clustered or otherwise distributed across multiple computing nodes. There are are identity creation patterns that can produce a completely unique identity. __________ (UUID), or globally unique identifier, is one such approach.

Universally unique identifier

The primary reasons to use ________ in the model are to check the correctness of any one attribute/property, any whole object, or any composition of objects.

Validation

It is the unique identity and mutability characteristics that set Entities apart from __________.

Value Objects

When deciding what should be in an Entity, only add the attributes that are ________ to your Bounded Context. For instance, following the example from the book, when the team was modeling the Tenant and User Entities, other attributes may be associated with each subscriber, such as a support contract and call activation PIN , billing and payment information, and maybe a business location along with customer contacts. But those are business concerns, not part of security. Attempting to stretch the Identity and Access Context too far would be a defeating effort.

essential


Related study sets

Health Assessment: chap 1-6 prepu

View Set

Chapter 44: Drug Therapy to Regulate Calcium and Bone Metabolism

View Set

First Computer Science Principles Test

View Set

Lesson 5: Installing and Configuring Routed Networks

View Set