A small thing, but I will be happy to hear what other people think about it.
Which of the 2 code segments below is the best programming practice?
var results = GetResults();
SendResults(results);
OR:
SendResults(GetResults());
I think that the first option is better, but on the other hand option 2 is less code to write (and read). What do you think?
I know it's a very basic question, but still...
no, there's nothing wrong with that at all, and in js, it's usually a good thing. the inside functions may not be a pure function, if they rely on closure variables. If you don't need a closure or don't need to worry about polluting your namespace, write it as a sibling.
A nested function can access other local functions, variables, constants, types, classes, etc. that are in the same scope, or in any enclosing scope, without explicit parameter passing, which greatly simplifies passing data into and out of the nested function. This is typically allowed for both reading and writing.
Nested function calls simply means that one function can call another which in turn can call another.
This
var results = GetResults();
SendResults(results);
is better because it's debuggable... Try putting a breakpoin on SendResults(results)
and watch the value of results.
This is so much important that in the next version of Visual Studio, the 2013 they are adding a way to see return value of functions (see for example here)
This new feature allows you to examine the return value of a function when the developer steps over or out of a function during your debugging session. This is especially useful when the returned value is not stored in a local variable. Consider the following nested function example Foo(Bar()); in this example you can now examine the return value(s) from Bar and Foo, when you step over that line.
From a compiled perspective they are normally the same. The only difference at the IL level is that a slot in the stack has some metainformation with the name of the variable (results
) or is nameless.
In my opinion you have to always strive for clarity, so I'd much rather have:
// notice the type not var (unless it's obvious)
IEnumerable<MyClass> results = GetResults();
SendResults(results);
I usually go for the first option, because that way I can insert a breakpoint between the invocations of GetResults
and SendResults
.
It's usually not that big of a deal, if the code is in the middle of a method, but if it's in the form of:
return Process(GetData());
the return values of both the GetData
and the Process
calls are not readily visible. Unless we are talking of a framework function that has no side effects and has obvious results (e.g. int.Parse) I prefer the format:
var data = GetData();
var result = Process(data);
return result;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With