The ignoring toString() method
Consider the following Apex class:
public class ToStringDemo {
public String companyName {get;set;}
public String city {get;set;}
}
A developer can print any important information about this class by running the following anonymous Apex code:
ToStringDemo obj = new ToStringDemo(); obj.companyName = 'Salesforce'; obj.city = 'SFO'; System.debug(obj);
The output is as follows:
ToStringDemo:[city=SFO, companyName=Salesforce]
In the preceding code, we are trying to print an object for debugging purposes. Internally, Apex calls the toString()
method. As we have not overridden it, Salesforce uses its predefined className:[variable1=value,variable2=value,...]
format to print the object value:
Ignoring the override of the toString()
method is considered as an anti-pattern and we should implement it whenever possible.
Note
Every class in Apex is by default a child of the Object
class. So, all the classes inherit...