I'm working on a third-party API integration and whilst modeling the relationship between classes and objects, I hit a roadblock.
I need to write Apex classes that have the same namespace as standard or custom objects. Doing so will allow me to add custom states and behaviors that are relevant to the implementation, while making the code easy to understand.
For example, say that inside of my implementation wrapper class I want to write an Apex class called Contact
. I noticed that the documentation gives an example of using the System
namespace to disambiguate between local and system scope namespaces.
public class ThirdPartyIntegration {
public class Contact {
// Access the Contact in the default namespace
public System.Contact proxy {get;set;}
public Contact() {
this.proxy = new System.Contact();
}
public asJson() {
// convert proxy to a JSON string
}
}
}
Inside of this Contact
class I could add any behaviors that are needed. For simplicity let's say that I want to add an instance method that converts the instance into a JSON string specifically shaped for the third party API. From within the wrapper class, I would be able call an instance method on my custom Apex Contact class like so:
// Instantiate a contact
Contact myContact = new Contact();
myContact.proxy.FieldOne__c = 'example one';
myContact.proxy.FieldTwo__c = 'example two';
// Call the `asJSON` method on the contact
// Return a JSON string shaped for the third party API
myContact.asJSON;
// Output: '{field_one: ['example_one'], field_two: {attribute_one: 'example two'}}'
Is it okay to do this? I can see a lot of benefit to using the same names for my classes, namely encapsulating all say System.Contact
code under the Contact
class.