Domain classes in Apex compared to other platforms

As we have seen in earlier chapters, a Standard or Custom Object is exposed within the Apex runtime as a concrete type that can be instantiated to populate record fields for insertions in the database or to determine which types are used to return records queried from it.

When considering the Domain pattern, the first inclination is perhaps to extend the applicable SObject, such as Account or Race__c through Apex inheritance with the extends keyword. Unfortunately, the Apex compiler does not support this approach. Even if it were to support this, given the best practices of bulkification, writing code that deals with a single record instance at a time will quickly lead to governor issues.

Instead, the Domain class implementation covered here uses the composition approach to combine record data and behavior. This is sometimes known as the wrapper class approach; it is so named because it wraps the data that it relates to as a class member variable.

The Apex implementation of the wrapper class is no different, except that we choose to wrap a list of records to enforce bulkified implementations of the logic within. The following pseudocode illustrates the instantiation of an Apex Domain class:

List<Race__c> raceRecords = 
[select Id, Name from Races__c where Id in :raceIds]; Races races = new Races(raceRecords);

Another implementation difference compared to other platforms, such as Java and .NET, is the creation of accessor methods to obtain related parent and child records. Though it is possible to write such methods, they are not recommended; for example, Contestants.getRaces or Races.getContestants.

This implementation avoids coding these types of accessors, as the SObject objects in Apex already provide a means to traverse relationships (if queried) as needed. The bulk nature of Apex Domain classes also makes these types of methods less useful and it is more appropriate for the caller to use the Selector classes to query the required records as and when needed, rather than as a result of invoking an accessor method.

To summarize, the Apex Domain classes described in this chapter focus on wrapping lists of records and methods that encapsulate the object's behavior and avoid providing accessor methods for query-related records.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.61.30