apex-enterprise-patterns / fflib-apex-common

Common Apex Library supporting Apex Enterprise Patterns and much more!
BSD 3-Clause "New" or "Revised" License
903 stars 514 forks source link

Fix bug in the getChangedRecords method #387

Closed wimvelzeboer closed 2 years ago

wimvelzeboer commented 2 years ago

A colleague at work found an issue with the getChangedRecords method, it is not listing records as changed when only a casing is different in a field. e.g. LastName field changed from "smith" to "Smith".

e.g.: This fails: as it outputs "Not Changed"'

Contact r1 = new Contact(LastName = 'Test');
Contact r2 = new Contact(LastName = 'test');
SObjectField fieldName = Contact.LastName;
if (r1.get(fieldName) != r2.get(fieldName))
{
    System.debug('Changed');
} else 
{
   System.debug('Not Changed');
}

while this works:

Contact r1 = new Contact(LastName = 'Test');
Contact r2 = new Contact(LastName = 'test');
SObjectField fieldName = Contact.LastName;
if (r1.get(fieldName) !== r2.get(fieldName))
{
    System.debug('Changed');
} else 
{
   System.debug('Not Changed');
}

So, instead of != we need to use !==

CC: @stohn777 @daveespo @ImJohnMDaniel


This change is Reviewable

wimvelzeboer commented 2 years ago

While that might work for String, it doesn't work for other Objects.

Opportunity o1 = new Opportunity(CloseDate=Date.newInstance(2022,1,1));
Opportunity o2 = new Opportunity(CloseDate=Date.newInstance(2022,1,1));
System.assert(o1.get('CloseDate') == o2.get('CloseDate')); //Pass
System.assert(o1.get('CloseDate') === o2.get('CloseDate')); //Fail

This solution needs reworking

@daveespo Ah, I should have thought of that.. I now pushed another change that does fix it for string fields only.

stohn777 commented 2 years ago

Perhaps not. Evidently Object.equals(...) with a String does not work as this logic would need. Explicit code for a String would still be needed.

Object base = 'true';
Object same = 'true';
Object diff = 'True';

// Passes
System.assert(base.equals(same), 'Values are different.  Expected: ' + base.toString() + ' Actual: ' + same.toString());

// Fails
System.assert(!base.equals(diff), 'Values are equal.  Expected: ' + base.toString() + ' Actual: ' + diff.toString());