5

During a conference call with a collegue, I saw him using list of Strings while using Ids, referencing to a list of Ids ; I asked him why this choice, he answered 'Ids are strings so it's about the same'.

Naturally, I would use List<Id> idList rather than List<String> idList .

Are they really differences, and uses cases where we really have to think about the use of the lists, to choose between one case rather than the other ?

  • 3
    use List<Id> - much better self-documented code; built-in error checking; built in IDE support for available methods. – cropredy Jul 31 '19 at 17:14
9

Both String and Id are primitive data types in apex. Consider below scenario:

public class poc {
    static List<Id> ids = new List<Id>();
    public static void check() {
        try {
            ids.add('invalid_id');
            System.debug('ids => '+ids);
        }
        catch(Exception ex) {
            System.debug('ERROR => '+ex.getMessage());
        }
    }   
}

Here when you invoke check(), it will throw error saying Invalid id: invalid_id as 'invalid_id' is actually not a valid salesforce Id.

However when you define List<String> variable and add Id to that variable, apex internally converts Id datatype to String and adds it.

IMPORTANT:

  1. When you expect a collection to have Ids, then always define use type Id only so that you do not add string inadvertantly. This is a best practice.

  2. When you dont know which data type it may contain, you can use String and later convert String to Id using Id.valueOf(String). But before converting, it is best practice to check if its valid Id using instanceof. Example below:

    System.debug('aa' instanceof Id); //false
    System.debug('0010K00001fr5LhQAI' instanceof Id); //true
    
| improve this answer | |
2

Ids are a subset of Strings. The advantage of using Id is that it has its own methods that you could use from here:

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_id.htm

But in a lot of cases I'd say it's not that big of a deal if you use string instead of Id. I try to use Id if I know for sure it is an Id. I think it makes the code cleaner

| improve this answer | |

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.