Most programmers coming from a standard object oriented programming programming language like Java, C#, C++ etc. are used to working with composite objects. For e.g. an Account object will contain a list of associated Contacts and Cases. A Project object will have a list of associated tasks.

When you start working with the platform, the behavior of objects for both standard and custom objects is not what you would intuitively expect. If you query the system with the right SOQL queries, you will be able to get back a composite object. On the contrary, if you instantiate a new parent object instance, the associated child objects do not automatically show up in there.

This confounds new developers when they start writing custom code with Apex. Let us say that you have a situation where you have to collect a list of parent and child objects from the user or a bulk load process, and then persist them to the database. The inability to instantiate composite objects that represent your data model will force you to collect each object in a separate set of lists and save each list separately, while taking care to set the parent lookup ids for each object correctly.

The way to solve this on the platform is to use “wrapper classes”. You can define a wrapper class in Apex that is a composite of the parent object and it’s related list of child objects. For e.g., AccountWrapper would be a class that contains the parent Account object instance and a list of associated contacts and cases, or ProjectWrapper would contain the parent Project instance and it’s related Tasks list.

This approach allows you to instantiate an object that represent the account or project parent object and it’s related lists that simulates what you are used to with object composition on other platforms. The work of mapping account ids to it’s associated contacts and cases is no longer a set of for loops that can be prone to programming errors.