0

What will be the best option for resolving the hard coded Ids in Salesforce APEX classes?

  1. Introduce a Custom metadata type to store the value and retrieve it in the Apex.
  2. Introduce a Custom setting to store the value and retrieve it in the Apex.
  3. Add the hardcoded values in a custom label and retrieve it in the Apex.
2
  • 1
    Are you sure you mean ids? Or your question is to just keep general info/text/setting which should not be hard-coded? – Ayub May 4 '20 at 13:20
  • In this case, I am talking about Ids only. – Hariprasath May 4 '20 at 13:23
4

None of the above. Any of the approaches you list still make use of hard-coded Ids, just in a configurable way. You should instead query for the data, preferably based on a unique field which is consistent across all your environments.

0
4

If the Ids you plan to hard-code are about recordTypes, I would suggest to use the following (I broke it down in multiple lines because it was quite long)

Schema
    .SObjectType
    .<yourSobject>
    .getRecordTypeInfosByDeveloperName()
    .get('YouRecordTypeDeveloperName')
    .getRecordTypeId();

From the doc

(I prefer getRecordTypeInfosByDeveloperName over the getRecordTypeInfosByName because admins are way more careful when modifying Api names than labels)


If they are just record-based be careful while "parametrazing a hard-code". That is not a best practice, you will specially suffer with sandbox refreshes, as recordIds are not always replicated (depending on the sandbox type) and also Test classes, which will force you to have "ViewAllData", which is also not recommended.

You can try to minimise the impact of the queries (if you need multiple) by using the cache, but as mentioned before, In controllers and batches is not likely that you cross that limit (worse-case scenario, pre-query them in the controller / constructor / start.

On a side-note, if they are "record-based", I would assume that you plan to have many records pointing to a small group of records (eg. having an account called "Inactive"). Be careful with that. I recommend you reading a bit about Lookup Skew

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.