Each issue of "The Architect" will address a common problem in object-oriented programming. This month, we will take a look at how to get a reference to an instance of the class that you would like to use in your code.
Potluck Principle of Getting Objects You Want
If you want to get a reference to an instance of the class, you should first understand what type of object you are trying to create. Is it an Entity, Value Object, DTO, or something else? Once you answered this question, select one of the options below. Choose the option that better fits your situation:
- You may be able to create the object yourself
- You may be able to ask another object to give the object to you
- You may be able to reconstitute the object from a previously stored state
When I discussed these options with Svetlana, she said that they reminded her of organizing a potluck. Potluck suggests an assortment of dishes, just like an object-oriented code is an assortment of objects. When you want a particular dish to be prepared for a potluck, you can do it yourself, assign it to one of the guests, or pick it up from a local grocery or a restaurant.
Option 1: Create the object yourself
You can create the object yourself by calling its constructor or using one of the Creational Design Patterns. Here are some examples when it may be applicable:
- New Entity. Entity, aka Reference Object, is an object defined by its identity as opposed to its attributes. Examples: a new Account, a new Person, a new Application.
- Value Object. Value Object is an element of the domain model with no concept of identity. Examples: Money, DayPoint, Address.
- Policy, Specification, or another member of the Decision Making layer. Examples: IsCosignableApplicationSpecification, IsEligibleFor401KEmployeeSpecification.
- Data Transfer Object
Option 2: Ask another object to give the object to you
Here are the examples:
- Local Entity inside of an Aggregate. Aggregate is a cluster of associated objects treated as a unit for the purposes of data changes. The root is the only member of the aggregate that outside objects are allowed to hold references to. To find an object inside the aggregate, you need to traverse its associations. Examples: Order Items of a Purchase Order, Wheels of a Car.
- Value Object used to describe an Entity or another Value Object. Examples: Age of a Person, Amount in a Bank Account.
Option 3: Reconstitute the object from a previously stored state
- Existing Aggregate or Global Entity. For each aggregate (or global entity) in your domain model, create a repository responsible for performing a database query and recreating the aggregate (or global entity) based on the query results. Examples: a Car, an Application.
Note that the Potluck Principle does not attempt to answer where and when object references may be obtained and how long they can be kept in memory. These are good themes for our future blog articles.
Let me know what you think. Happy coding!