[SalesForce] How To Avoid Hard Coding ID

Basically, I have three custom objects:

Object1__c : Id, Name, Field1__c
Object2__c : Id, Name, Object1__c, Type__c (TypeA,TypeB)
Object3__c : Id, Name, Object2__c

I created custom lookup fields to build relationship among the objects.

Every time a new Object3__c is inserted, a new Object2__c must be created. Here's a sample scenario to make things clearer:

Sample Object1__c record :
  Object1 Name: ABC
  Field1: This is just a sample field. 

Sample Object2__c record :
  Object2 Name: O2-{00001}
  Object1: ABC
  Type: TypeA

Sample Object3__c record :
  Object3 Name: O3-{00001}
  Object2: 02-{00001}

Now, a new Object2__c record must be created, but this time, Object1__c lookup field must be ALWAYS equal to this value: DEF. But remember that this is a lookup field, so I made sure that there's an Object1__c record with this name:

Sample Object1__c record :
      Object1 Name: DEF
      Field1: This is a sample field1 value.

Assume that I already have this record. Now, to create new Object2__c record, I just assigned a Object1__c field the Id of the above record (DEF record) like this:

o2.Object1__c = 'a0sp0000008zHMw';

But someone told me that this is not a good practice.

How can I handle this kind of scenario without hardcoding the record Id?

Best Answer

If I'm understanding you correctly, you have an object with a lookup field that you always want to associate to the same record. If that is the case, then there must be something distinguishing that record, for example its name. In that case, you would build a query and then reference the returned Id.

Object1__c o1 = [SELECT Id FROM Object1__c WHERE Name = :'DEF' LIMIT 1];
Object2__c o2 = new Object2__c();
o2.Object1__c = o1.Id;

It is true that hard-coding an Id is bad practice. Let's look at why. Here are a few scenarios:

  1. If you are planning on migrating this to another environment (sandbox to sandbox or production) then the ID of your record will change. What will work in SandboxA won't work in SandboxB because even if you create the exact same record, the ID will be different.
  2. If you delete that record, you have to go fix all of your hard-coded Ids. That is difficult to manage.
  3. Say that someone deletes your record. Obviously that would result in a few errors in your code. Hopefully what you would do with your query is then check to make sure there is a record that is being returned, and if not, you can handle the error properly.
  4. It makes your code less understandable. No one has any idea what 'aBbb0000000PBvNCAW' refers to until they go look up that record (which may be difficult if you made the record in one environment and they are in another.) With a query, another developer (or future you) will be able to understand that you are getting a record with the name 'DEF'.
Related Topic