[SalesForce] How to efficiently determine the `name` field of an sobject for dynamic query

Is there a more efficient way to determine the name field of an sobject other than iterating through all the fields obtained via DescribeSOBjectResult?

Often, the name field is simply Name but in some occasions with standard objects it is not. For example, Case's name field is CaseNumber.

Here is the apex method I'm using, but seems inefficient to loop through all the fields:

public String getNameField( SObjectType sobjectType ) {

    DescribeSObjectResult objDescribe = sobjectType.getDescribe();

    Map<String, SObjectField> fieldsMap = objDescribe.fields.getMap();

    for ( SObjectField fieldToken : fieldsMap.values() ) {

        DescribeFieldResult fieldDescribe = fieldToken.getDescribe();

        if ( fieldDescribe.isNameField() ) {
            return fieldDescribe.getName();
        }

    }

    return 'Name'; // default
}

Best Answer

Elegant? Perhaps not, but checking 'Name' first and only iterating as a fallback plan should be more efficient. With every custom object and most standard objects, this shortcut will cut out the looping and additional describes entirely.

My natural inclination is to start with a positive condition:

public static String getNameField(SObjectType sObjectType)
{
    Map<String, SObjectField> fields = sObjectType.getDescribe().fields.getMap();
    if (fields.containsKey('Name') && fields.get('Name').getDescribe().isNameField())
    {
        return 'Name';
    }

    // iteration logic

    return 'Name'; // fallback if iteration fails
}

It may be more elegant, however, to use a negative condition and DRY on the return 'Name' front.

public static String getNameField(SObjectType sObjectType)
{
    Map<String, SObjectField> fields = sObjectType.getDescribe().fields.getMap();
    if (!fields.containsKey('Name') || !fields.get('Name').getDescribe().isNameField())
    {
        // iteration logic
    }
    return 'Name';
}