Chapter 4. Manipulating objects

 

This chapter covers

  • Making a distinction between mutable and immutable objects
  • Using modifier methods to change state or create modified copies
  • Comparing objects
  • Protecting against invalid state changes
  • Using events to track changes in mutable objects

As you’ve learned in the previous chapters, services should be designed to be immutable. This means that once a service object has been created, it can never be modified. The biggest advantage is that its behavior will be predictable, and it can be reused to perform the same task using different input.

So we know that services should be immutable objects, but what about the other types of objects: entities, value objects, and data transfer objects?

4.1. Entities: Identifiable objects that track changes and record events

Entities are the application’s core objects. They represent important concepts from the business domain, like a reservation, an order, an invoice, a product, a customer, etc. They model knowledge that developers have gained about that business domain. An entity holds the relevant data, it may offer ways to manipulate that data, and it may expose some useful information based on that data. An example of an entity is the following SalesInvoice class.

4.2. Value objects: Replaceable, anonymous, and immutable values

4.3. Data transfer objects: Simple objects with fewer design rules

4.4. Prefer immutable objects

4.5. A modifier on an immutable object should return a modified copy

4.6. On a mutable object, modifier methods should be command methods

4.7. On an immutable object, modifier methods should have declarative names

4.8. Compare whole objects

4.9. When comparing immutable objects, assert equality, not sameness

4.10. Calling a modifier method should always result in a valid object

4.11. A modifier method should verify that the requested state change is valid

4.12. Use internally recorded events to verify changes on mutable objects

4.13. Don’t implement fluent interfaces on mutable objects

Summary

Answers to the exercises

sitemap