Is good to call function in other function parameter?

后端 未结 3 1807
囚心锁ツ
囚心锁ツ 2021-01-16 08:13

I suppose this:

public static string abc()
{
    return \"abc\";
}

Is better to call this function in this way:

string call         


        
相关标签:
3条回答
  • 2021-01-16 08:57

    Actually I don't see a difference if you don't have any error checking.

    This would make a difference

    string call = abc();
    # if call is not empty
    {
        Console.writeline(call);
    }
    

    The above method could avoid empty string being written.

    0 讨论(0)
  • 2021-01-16 09:01

    Both are valid. However, out of experience I have concluded that the first option is more suitable for readability and ease of maintenance. I can't count how many times I have changed from the "compact" style to the first one as a help for a debugging session.

    For example, this style makes it easy to check the correctness intermediate of an intermediate result:

    string call = abc();
    assert(!call.empty()); // Just an example.
    Console.writeline(call);
    

    Also, it helps to make the code more robust later, adding a conditional check before the subsequent action that checks call's value, for example if the design does not guarantee that the condition of the previous assert holds but you still need to check it.

    string call = abc();
    if (!call.empty())
    {
        Console.writeline(call);
    }
    

    Note also that with this style you will be able to easily inspect the value of call in your debugger.

    0 讨论(0)
  • 2021-01-16 09:11

    Given your exact example (one parameter, value not used elsewhere, no side effects), it's just a matter of style. However, it gets more interesting if there are multiple parameters and the methods have side effects. For example:

    int counter;
    
    int Inc() { counter += 1; return counter }
    
    void Foo(int a, int b) { Console.WriteLine(a + " " + b); }
    
    void Bar()
    {
        Foo(Inc(), Inc());
    }
    

    What would you expect Foo to print here? Depending on the language there might not even be a predictable result. In this situation, assigning the values to a variable first should cause the compiler (depending on language) to evaluate the calls in a predictable order.

    0 讨论(0)
提交回复
热议问题