Drawbacks of using SObjectField.toString() over SObjectField.getDescribe().getName()












10















I often do '' + field where field is an SObjectField to get the field's API name. I like that much more than the clunky verbose field.getDescribe().getName().



So is there a reason I should not do it using the toString() method? Will Salesforce change the output eventually?










share|improve this question


















  • 1





    Type coercion is not at all the same as calling toString. You do have issues around null-safety potentially, depending on where the input is coming from.

    – Adrian Larson
    2 days ago
















10















I often do '' + field where field is an SObjectField to get the field's API name. I like that much more than the clunky verbose field.getDescribe().getName().



So is there a reason I should not do it using the toString() method? Will Salesforce change the output eventually?










share|improve this question


















  • 1





    Type coercion is not at all the same as calling toString. You do have issues around null-safety potentially, depending on where the input is coming from.

    – Adrian Larson
    2 days ago














10












10








10








I often do '' + field where field is an SObjectField to get the field's API name. I like that much more than the clunky verbose field.getDescribe().getName().



So is there a reason I should not do it using the toString() method? Will Salesforce change the output eventually?










share|improve this question














I often do '' + field where field is an SObjectField to get the field's API name. I like that much more than the clunky verbose field.getDescribe().getName().



So is there a reason I should not do it using the toString() method? Will Salesforce change the output eventually?







apex performance describesobject






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 2 days ago









Robert SösemannRobert Sösemann

12.8k1076210




12.8k1076210








  • 1





    Type coercion is not at all the same as calling toString. You do have issues around null-safety potentially, depending on where the input is coming from.

    – Adrian Larson
    2 days ago














  • 1





    Type coercion is not at all the same as calling toString. You do have issues around null-safety potentially, depending on where the input is coming from.

    – Adrian Larson
    2 days ago








1




1





Type coercion is not at all the same as calling toString. You do have issues around null-safety potentially, depending on where the input is coming from.

– Adrian Larson
2 days ago





Type coercion is not at all the same as calling toString. You do have issues around null-safety potentially, depending on where the input is coming from.

– Adrian Larson
2 days ago










1 Answer
1






active

oldest

votes


















8















So is there a reason I should not do it using the toString() method?




String concatenation isn't strictly the same as toString() in Apex. For one thing, many things that should have a toString() do not actually have one, but instead have to be evaluated through String.valueOf(Object param) instead.



This is a marked difference compared to Java, where Object, the parent of all other objects, has a functional toString() of its own. One example of this I found was through String.join, which logically sounds like it should use toString() where available, but doesn't, leading to some surprising output.



class demo {
public override string toString() {
return 'Hello';
}
}
System.debug(
String.join(new demo { new demo() }, '')
);


Output:




USER_DEBUG [6]|DEBUG|anon$demo




Using string concatenation reduces CPU and heap usage by a minuscule amount, though it could add up in large loops. The only difference real difference between the two is one would give you a string 'null' (concatenation) while the other would throw a NullPointerException (by reference).



If there's one thing I'd call a drawback is that using string concatenation dynamically with null values could lead to spurious errors elsewhere in your code, such as 'invalid field null in query' or something. At least with a NullPointerException, you already immediately know which line was the cause instead of some bizarre error down the line.




Will Salesforce change the output eventually?




Salesforce couldn't easily change this behavior, because it is very widespread in usage. At best, they could only make a versioned change (e.g. it behaves differently in a hypothetical version 99.0 versus 98.0), otherwise it could cause all sorts of havoc. It's easier to just let the behavior stay the way it is.






share|improve this answer























    Your Answer








    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "459"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f247885%2fdrawbacks-of-using-sobjectfield-tostring-over-sobjectfield-getdescribe-getna%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    8















    So is there a reason I should not do it using the toString() method?




    String concatenation isn't strictly the same as toString() in Apex. For one thing, many things that should have a toString() do not actually have one, but instead have to be evaluated through String.valueOf(Object param) instead.



    This is a marked difference compared to Java, where Object, the parent of all other objects, has a functional toString() of its own. One example of this I found was through String.join, which logically sounds like it should use toString() where available, but doesn't, leading to some surprising output.



    class demo {
    public override string toString() {
    return 'Hello';
    }
    }
    System.debug(
    String.join(new demo { new demo() }, '')
    );


    Output:




    USER_DEBUG [6]|DEBUG|anon$demo




    Using string concatenation reduces CPU and heap usage by a minuscule amount, though it could add up in large loops. The only difference real difference between the two is one would give you a string 'null' (concatenation) while the other would throw a NullPointerException (by reference).



    If there's one thing I'd call a drawback is that using string concatenation dynamically with null values could lead to spurious errors elsewhere in your code, such as 'invalid field null in query' or something. At least with a NullPointerException, you already immediately know which line was the cause instead of some bizarre error down the line.




    Will Salesforce change the output eventually?




    Salesforce couldn't easily change this behavior, because it is very widespread in usage. At best, they could only make a versioned change (e.g. it behaves differently in a hypothetical version 99.0 versus 98.0), otherwise it could cause all sorts of havoc. It's easier to just let the behavior stay the way it is.






    share|improve this answer




























      8















      So is there a reason I should not do it using the toString() method?




      String concatenation isn't strictly the same as toString() in Apex. For one thing, many things that should have a toString() do not actually have one, but instead have to be evaluated through String.valueOf(Object param) instead.



      This is a marked difference compared to Java, where Object, the parent of all other objects, has a functional toString() of its own. One example of this I found was through String.join, which logically sounds like it should use toString() where available, but doesn't, leading to some surprising output.



      class demo {
      public override string toString() {
      return 'Hello';
      }
      }
      System.debug(
      String.join(new demo { new demo() }, '')
      );


      Output:




      USER_DEBUG [6]|DEBUG|anon$demo




      Using string concatenation reduces CPU and heap usage by a minuscule amount, though it could add up in large loops. The only difference real difference between the two is one would give you a string 'null' (concatenation) while the other would throw a NullPointerException (by reference).



      If there's one thing I'd call a drawback is that using string concatenation dynamically with null values could lead to spurious errors elsewhere in your code, such as 'invalid field null in query' or something. At least with a NullPointerException, you already immediately know which line was the cause instead of some bizarre error down the line.




      Will Salesforce change the output eventually?




      Salesforce couldn't easily change this behavior, because it is very widespread in usage. At best, they could only make a versioned change (e.g. it behaves differently in a hypothetical version 99.0 versus 98.0), otherwise it could cause all sorts of havoc. It's easier to just let the behavior stay the way it is.






      share|improve this answer


























        8












        8








        8








        So is there a reason I should not do it using the toString() method?




        String concatenation isn't strictly the same as toString() in Apex. For one thing, many things that should have a toString() do not actually have one, but instead have to be evaluated through String.valueOf(Object param) instead.



        This is a marked difference compared to Java, where Object, the parent of all other objects, has a functional toString() of its own. One example of this I found was through String.join, which logically sounds like it should use toString() where available, but doesn't, leading to some surprising output.



        class demo {
        public override string toString() {
        return 'Hello';
        }
        }
        System.debug(
        String.join(new demo { new demo() }, '')
        );


        Output:




        USER_DEBUG [6]|DEBUG|anon$demo




        Using string concatenation reduces CPU and heap usage by a minuscule amount, though it could add up in large loops. The only difference real difference between the two is one would give you a string 'null' (concatenation) while the other would throw a NullPointerException (by reference).



        If there's one thing I'd call a drawback is that using string concatenation dynamically with null values could lead to spurious errors elsewhere in your code, such as 'invalid field null in query' or something. At least with a NullPointerException, you already immediately know which line was the cause instead of some bizarre error down the line.




        Will Salesforce change the output eventually?




        Salesforce couldn't easily change this behavior, because it is very widespread in usage. At best, they could only make a versioned change (e.g. it behaves differently in a hypothetical version 99.0 versus 98.0), otherwise it could cause all sorts of havoc. It's easier to just let the behavior stay the way it is.






        share|improve this answer














        So is there a reason I should not do it using the toString() method?




        String concatenation isn't strictly the same as toString() in Apex. For one thing, many things that should have a toString() do not actually have one, but instead have to be evaluated through String.valueOf(Object param) instead.



        This is a marked difference compared to Java, where Object, the parent of all other objects, has a functional toString() of its own. One example of this I found was through String.join, which logically sounds like it should use toString() where available, but doesn't, leading to some surprising output.



        class demo {
        public override string toString() {
        return 'Hello';
        }
        }
        System.debug(
        String.join(new demo { new demo() }, '')
        );


        Output:




        USER_DEBUG [6]|DEBUG|anon$demo




        Using string concatenation reduces CPU and heap usage by a minuscule amount, though it could add up in large loops. The only difference real difference between the two is one would give you a string 'null' (concatenation) while the other would throw a NullPointerException (by reference).



        If there's one thing I'd call a drawback is that using string concatenation dynamically with null values could lead to spurious errors elsewhere in your code, such as 'invalid field null in query' or something. At least with a NullPointerException, you already immediately know which line was the cause instead of some bizarre error down the line.




        Will Salesforce change the output eventually?




        Salesforce couldn't easily change this behavior, because it is very widespread in usage. At best, they could only make a versioned change (e.g. it behaves differently in a hypothetical version 99.0 versus 98.0), otherwise it could cause all sorts of havoc. It's easier to just let the behavior stay the way it is.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 2 days ago









        sfdcfoxsfdcfox

        252k11194432




        252k11194432






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Salesforce Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f247885%2fdrawbacks-of-using-sobjectfield-tostring-over-sobjectfield-getdescribe-getna%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

            Alcedinidae

            Origin of the phrase “under your belt”?