Is good to call function in other function parameter?

不打扰是莪最后的温柔 提交于 2020-01-30 01:14:35

问题


I suppose this:

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

Is better to call this function in this way:

string call = abc();
Console.writeline(call);

Than this?

console.writeline(abc());

is there any reason to prefer one to the other?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/16710263/is-good-to-call-function-in-other-function-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!