Chapter 3. Creating other objects

 

This chapter covers

  • Instantiating other types of objects
  • Preventing objects from being incomplete
  • Protecting domain invariants
  • Using named constructors
  • Using assertions

I mentioned earlier that there are two types of objects: services and other objects. The second type of objects can be divided into more specific subtypes, namely value objects and entities (sometimes known as “models”). Services will create or retrieve entities, manipulate them, or pass them on to other services. They will also create value objects and pass them on as method arguments, or create modified copies of them. In this sense, entities and value objects are the materials that services use to perform their tasks.

In chapter 2 we looked at how a service object should be created. In this chapter, we’ll look at the rules for creating these other objects.

3.1. Require the minimum amount of data needed 3.1 to behave consistently

Take a look at the following Position class.

3.2. Require data that is meaningful

3.3. Don’t use custom exception classes for invalid argument exceptions

3.4. Test for specific invalid argument exceptions by analyzing the ex- xception’s message

3.5. Extract new objects to prevent domain invariants from being verif- fied in multiple places

3.6. Extract new objects to represent composite values

3.7. Use assertions to validate constructor arguments

3.8. Don’t inject dependencies; optionally pass them as method arguments

3.9. Use named constructors

3.10. Don’t use property fillers

3.11. Don’t put anything more into an object than it needs

3.12. Don’t test constructors

3.13. The exception to the rule: Data transfer objects

Summary

Answers to the exercises