Salesforce Cookies #4

Never store record’s Id as a String (Variable type) if you are comparing Ids in your Apex code

If you are writing apex code then make sure that you are treating Ids’ carefully.¬† You should emphasize on declaring your variables of Id-type instead of String since storing record Id in a variable which type is Id will do the 15-character Id to 18-character Id conversion. Let’s take an example.

Code uses String type variable for holding record Ids
Map<String, Opportunity> mapOpportunities = new Map<String, Opportunity>();
mapOpportunities.put('006w000000tVvtt', Opp);
006w000000tVvtt - 15_Character_Opp_Id  

String oppRecordId = '006w000000tVvttAAG';
mapOpportunities.containsKey( oppRecordId ); // Will return False
006w000000tVvttAAG - 18_Character_Opp_Id

// Same as above 
String character_15_id = '006w000000tVvtt';
String character_18_id = '006w000000tVvttAAG';
character_15_id == character_18_id  // return false
Code uses Id type variable for holding record Ids
Map<Id, Opportunity> mapOpportunities = new Map<Id, Opportunity>();
mapOpportunities.put('006w000000tVvtt', Opp);
006w000000tVvtt - 15_Character_Opp_Id  
Id oppRecordId = '006w000000tVvttAAG';
// Performing containsKey operation will give you true 
// since declaring the map key as Id has done the required ID's conversion
mapOpportunities.containsKey( oppRecordId ); // Will return True
006w000000tVvttAAG - 18_Character_Opp_Id

// Same as above 
Id character_15_id = '006w000000tVvtt';
Id character_18_id = '006w000000tVvttAAG';
character_15_id == character_18_id // return true

Declaring such variables as Id will also help you to deal with invalid Ids. Happy coding!! ūüôā