How to use GetSObject to retrieve related data in a null safe manner?
You need to add a null check. The only reason this would fail is if your parent record is null. One option may be to just get the value statically:
String text = record.Parent__r.TextField__c;
If you cannot use a static reference, I recommend a cross object getter like I shared here. First create this top-level class:
public with sharing class CrossObject
{
public static Object get(SObject record, String field)
{
if (record == null) return null;
if (!field.contains('.')) return record.get(field);
return get(
record.getSObject(field.substringBefore('.')),
field.substringAfter('.')
);
}
}
Then instead of:
String text = (String)record.get('Parent__r').get('TextField__c');
You could use:
String text = (String)CrossObject.get(record, 'Parent__r.TextField__c');