This really depends on how much nesting you use. After all, you are allowed to use function results directly in expressions to improve readability. Both, code that does not use nested expressions (like assembler code), and code that uses too much nested expressions is hard to read. Good code tries to strike a balance in between the extremes.
So lets look at some examples. The one you gave in your question seems quite legit to me, so nothing to worry here. However, a line like
foo(bar(baz(moo, fab), bim(bam(ext, rel, woot, baz(moo, fab)), noob), bom, zak(bif)));
would definitely not be tolerable. Likewise, code like
double xsquare = x*x;
double ysquare = y*y;
double zsquare = z*z;
double xysquare = xsquare + ysquare;
double xyzsquare = xysquare + zsquare;
double length = sqrt(xyzsquare);
would not be very readable as well. sqrt(x*x + y*y + z*z) is much easier to understand, even though it combines a total of six different operation in one expression.
My advice is to pay attention to what expressions you can still parse in your head easily. The moment you need to take a second look to grasp what a single expression does, it's time to introduce an additional variable.
Answer from cmaster - reinstate monica on Stack ExchangeHey peeps,
I've been using js for a while now, but it only occurred to me recently that I should probably check that one of my habits isn't horrendously bad form or causing me memory/efficiency problems etc.
SO, here's the dilemma :
function setupExample(){
var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");
var button3 = document.getElementById("button3");
button1.addEventListener("click", toggleExampleOne);
button2.addEventListener("click", toggleExampleTwo);
button3.addEventListener("click", toggleExampleThree);
function toggleExampleOne(){
button1.classList.toggle("activated");
}//END toggleExampleOne
function toggleExampleTwo(event){
event.srcElement.classList.toggle("activated");
}//END toggleExampleTwo
}//END setupExample
function toggleExampleThree(event){
event.srcElement.classList.toggle("activated")
}//END toggleExampleThreeNow, I use a structure like this quite regularly - I tend to use example 1 in this case - but my concern now is that by referencing values outside the function called by the click event, the entirety of 'setupExample' would be kept in memory when all I actually need is the toggle functions!
Are example 2 or 3 better in this case, or am I worrying about nothing and there is absolutely no difference between the three?
Thanks in advance, peeps!
-P
Why do you think that nesting functions is bad form? Modern Javascript is often written in a class-like block structure, to make for ease of exporting.
As other commenters have observed, nested functions are "private" in the sense that you won't be able to access them directly. This is a feature, not a bug. It's really the cornerstone of object-oriented programming: by nesting related functions into the same shared block structure, you can vastly reduce the complexity of your code base.
This is the way I write JS code by default:
var basketModule = (function () {
// privates
var basket = [];
function doSomethingPrivate() {
//...
}
function doSomethingElsePrivate() {
//...
}
// Return an object exposed to the public
return {
// Add items to our basket
addItem: function( values ) {
basket.push(values);
},
// Get the count of items in the basket
getItemCount: function () {
return basket.length;
},
// Public alias to a private function
doSomething: doSomethingPrivate,
// Get the total value of items in the basket
getTotal: function () {
var q = this.getItemCount(),
p = 0;
while (q--) {
p += basket[q].price;
}
return p;
}
};
})();
This is similar to what in other languages is called a class.
What you're doing here is utilizing closures.
function toggleExampleOne(){
button1.classList.toggle("activated");
}//END toggleExampleOne
This is closing over the variable button1 in the outer scope. This will cause the function to be evaluated with this context every time it is called, which can be inefficient. There's a process you can do called lifting which flattens the closure - this is what your example three does.
However, I would largely not be too concerned about inefficiencies here. Micro-optimizations can quickly consume you: do what works best for making a maintainable application, then if you have performance problems, measure, and optimize your hot paths (the parts of your application that are used the most often). Especially so since most javascript engines are really quite optimized and will know how to transform your code in subtle ways to improve performance (like doing that lifting for you).
If you're worrying about cluttering up your global namespace though, look into modules or namespaces.
This really depends on how much nesting you use. After all, you are allowed to use function results directly in expressions to improve readability. Both, code that does not use nested expressions (like assembler code), and code that uses too much nested expressions is hard to read. Good code tries to strike a balance in between the extremes.
So lets look at some examples. The one you gave in your question seems quite legit to me, so nothing to worry here. However, a line like
foo(bar(baz(moo, fab), bim(bam(ext, rel, woot, baz(moo, fab)), noob), bom, zak(bif)));
would definitely not be tolerable. Likewise, code like
double xsquare = x*x;
double ysquare = y*y;
double zsquare = z*z;
double xysquare = xsquare + ysquare;
double xyzsquare = xysquare + zsquare;
double length = sqrt(xyzsquare);
would not be very readable as well. sqrt(x*x + y*y + z*z) is much easier to understand, even though it combines a total of six different operation in one expression.
My advice is to pay attention to what expressions you can still parse in your head easily. The moment you need to take a second look to grasp what a single expression does, it's time to introduce an additional variable.
The concept underlying your question is so important I feel it needs another answer rather than just a comment (as I had started to do).
The other 3 answers thus far provide some useful points of consideration on whether a given situation merits using what you call "nested function calls". But perhaps a more important point is hidden in the comments under your question: in case you missed the subtlety in what those erudite folks are suggesting, Carl, you have discovered for yourself the topic actually called functional programming. If you have never seen the term, you might not have thought it was really a "thing" in @HighPerformanceMark's comment.
But indeed it is! Functional programming has been written about for decades, since John Hughes' seminal paper Why Functional Programming Matters. There are some languages that are functional languages (i.e. they only let you write in a functional programming style), languages like Erlang, Lisp, OCaml, or Haskell. But there are many more languages that are hybrid imperative/functional languages. That is, they are traditionally imperative languages but offer some support for functional programming as well, including Perl, C++, Java, C#, and many more. Wikipedia's entry on functional programming provides a nice section showing a comparison of functional style vs. imperative style for a number of languages.
There is much to say on the differences between imperative and functional styles, but the key starting point is that with functional programming, functions or methods have no side effects, making it in general easier to both understand and debug programs.
For further reading, you might also take a look at Reginald Braithwaite's Why "Why Functional Programming Matters" Matters and another interesting post here on SO, Why functional languages?
One disadvantage of declaring a nested function is the fact that it will be created inside function's environment every time you call the parent function.
In theory, this could decrease performance if the parent function is called frequently.
But, nested functions are very much used in Javascript. For example, closures are extremely powerful and should be understood by all JavaScript developers.
More about closures
Nested functions have access to their parent scope so you could change state in a parent's scope from a deeply nested function. For example
function one() {
var a = 1;
two(); // a = 4
function two() {
var b = 2;
three(); // b = 4
function three() {
var c = 3;
four(); // c = 4
function four() {
a = 4;
b = 4;
c = 4;
}
}
}
}
On one hand this is pretty powerful. On the other hand it can easily get sloppy and hard to reason about because you have to make sure any child function hasn't changed a value in any of its parents.
If you stick to not nesting your functions you won't have to worry that the state inside your function is being changed from inside of a nested function.
function one() {
var a = 1;
two(); // a = 1
}
function two() {
var b = 2;
three(); // b = 2
}
function three() {
var c = 3;
four(); // c = 3
}
function four() {
a = 4;
b = 4;
c = 4;
}
Today on a PR I saw several functions defined within an str function, and I noted that that should be changed to meet best practices/pep8.
The submitter argued that it wasn't an issue, and sure enough I checked the pep8 and couldn't find a reference to it.
I could've sworn that nesting function declarations is looked down upon/bad practice in Python; am I right or am I just misremembering?
One disadvantage of declaring a nested function is the fact that it will be created inside function's environment every time you call the parent function.
In theory, this could decrease performance if the parent function is called frequently.
But, nested functions are very much used in Javascript. For example, closures are extremely powerful and should be understood by all JavaScript developers.
More about closures
Nested functions have access to their parent scope so you could change state in a parent's scope from a deeply nested function. For example
function one() {
var a = 1;
two(); // a = 4
function two() {
var b = 2;
three(); // b = 4
function three() {
var c = 3;
four(); // c = 4
function four() {
a = 4;
b = 4;
c = 4;
}
}
}
}
On one hand this is pretty powerful. On the other hand it can easily get sloppy and hard to reason about because you have to make sure any child function hasn't changed a value in any of its parents.
If you stick to not nesting your functions you won't have to worry that the state inside your function is being changed from inside of a nested function.
function one() {
var a = 1;
two(); // a = 1
}
function two() {
var b = 2;
three(); // b = 2
}
function three() {
var c = 3;
four(); // c = 3
}
function four() {
a = 4;
b = 4;
c = 4;
}
I may be calling this wrong, but all I mean is:
def func1():
def func2():I've seen posts explaining when you should use this, but I haven't found much against using it. I seem to be unintentionally using quite a few.
Is using a nested function best practice? Is it 'efficient'?
I only ask as my code seems to be running a little slow at the beginning, so trying to see if I can improve that
There are a lot of good reasons. Personally, I often use nested functions to keep the namespace clean. It's especially useful within object methods :
class Foo(object):
def bar(self):
def baz(val):
return val
return [ baz(i) for i in range(1,101) ]
If I declare baz outside of bar, I either need to make it a method of Foo, or expose it to the entire package.
I use a nested function to find matches from a list:
def get_exact(data, key, match):
def is_match(item):
if (key in item) and (item[key].lower() == match.lower()):
return item
return False
return [i for i in data if is_match(i)]
No other calls in the project have a need to use is_match(item), so why declare it separately?
However, I will say that, for my example, declaring is_match() outside of get_exact() does run around ~0.04 seconds faster in 10,000 iterations.
def is_match(item, key, match):
if (key in item) and (item[key].lower() == match.lower()):
return item
return False
def get_exact(data, key, match):
return [i for i in data if is_match(i, key, match)]
So, I am writing a main function (so that I can say if name == "main" because that is good practice). And my main file accesses a lot of classes that are not inside of the main function. This is all fine, but then there is a function in a number of different classes that I want to call at once. Think of it like: reset_box(), reset_circle(), reset_triangle() or whatever.
Under certain conditions I want to just hit all these at once. So, it would be nice to have a function I can call that just does them all at once rather than writing them all out each time.
It would be easiest to do this in the main function, to just add in another function that resets everything. Or is this bad code? Should I take the function out of main and call it that way? The downside of this is that I have to pass it every object that I want to reset which will make it look a little ugly?
What are people's thoughts? Is it better to have a little function inside main that I can call to reset a bunch of objects. Or does it seem better to have the function out of main and just pass in every object that I need to?
I have been writing a class which resembles a binary tree and have been looking to clean up my code a bit and found my way to nested functions. I understand the basic logic behind them and what not, my question is more on how they are used within custom objects.
For example, if i am trying to print the tree in-order and i do something like:
def print_inorder(self):
def display(node, level):
if not node:
return
display(node.left_child, level + 1)
print('\t' * level, node)
display(node.right_child, level + 1)
display(self.root, 0)Would this be correct best practices? The thing that is somewhat confusing to me is switching from using 'self.' for functions relating to the object, to an inner function that doesn't need a 'self.' even though an object is technically calling it. is this already best practice or should I still be using the 'self.'? or is there a better convention to use all together? Thanks.