0

I have this trigger that changes the Name of a record based on a custom title__c field:

trigger assignDegreeName on Degree__c (before insert) {
    /**
    Variables
    **/
    integer maxSize = 80;    

    /**
    Assign Name to new Degree
    **/
    for (Degree__c newDegree: Trigger.New) {
        string degreeName = newDegree.title__c;
        if (degreeName.length() > maxSize) {
            degreeName = degreeName.substring(0, maxSize);
        }

        newDegree.Name = degreeName;
    }
}

title__c is a required field, and I know that the endpoints we use to create Degrees will send an empty string, not null, for title anyways. So it should never be null and even if it is, it shouldn't get to this point in the trigger without failing in the first place because of the requirements.

Yet, I always get the error response attempt to de-reference a Null object on row 400 when I hit the api endpoint that uploads a bunch of degrees at once.

What could possibly be Null in this trigger?

4
  • Is this the only detail in the exception? What are other details which suggests the source of the exception? The only possible value that could throw that exception here seems to be degreeName. What do you see when you log a system.debug on newDegree.title__c, does it contain a null value at all?
    – Jayant Das
    Commented Apr 11, 2019 at 16:20
  • No, and it never should because it's a string, strings get casted as '' not null...
    – BlondeSwan
    Commented Apr 11, 2019 at 16:26
  • No. '' and null are different. '' is an empty string with size = 0. Strings don't get casted to '' if the value is null.
    – Jayant Das
    Commented Apr 11, 2019 at 16:29
  • So turns out, title__c gets set as "\u0646\u0638\u0645 \u0627\u0644\u0645\u0639\u0644\u0648\u0645\u0627\u062a \u0627\u0644\u062d\u0627\u0633\u0648\u0628\u064a\u0629" and that is what is being considered null
    – BlondeSwan
    Commented Apr 11, 2019 at 16:30

1 Answer 1

4

Never assume field values are not null, even those which are required. It is bad practice, and will throw NullPointerException rather than DmlException when the field is provided blank. It will screw with your unit tests, integrations, etc. Especially on insert triggers.

Your trigger will not see a difference between null and ''. Other best practices include moving your logic to an Apex Class. You should have a method that looks something like:

public with sharing class DegreeService
{
    public static void truncateTitles(List<Degree__c> records)
    {
        for (Degree__c record : records) truncateTitle(record);
    }
    public static void truncateTitle(Degree__c record)
    {
        if (record.Title__c == null) return;

        // now run your logic
    }
}
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .