So I’m just learning some new stuff in C# & Python. Turns out both lanuages support nested methods (C# sort of does).
Python:
def MyMethod():
print 'Hello from a method.'
def MyInnerMethod():
print 'Hello from a nested method.'
MyInnerMethod()
C# (using new features in .NET 3.5):*
static void Main()
{
Console.WriteLine("Hello from main.");
Func<int, int> NestedMethod =
(x) =>
{
Console.WriteLine("In nested method. Value of x is {0}.", x);
return x;
};
int result = NestedMethod(3);
}
So why are nested methods so important? What makes them useful?
**The C# code has not been tested. Feel free to edit if it doesn’t compile.*
First, realize I cannot give you a complete list. If you were to ask “why are screwdrivers useful?”, I would would talk about screws and paint can lids but would miss their value in termite inspection. When you ask, “Why are nested functions useful?”, I can tell you about scoping, closures, and entry points.
First, nesting can be an alternative to classes. I recently wrote some rendering code that took a file name for specialized mark-up code and returned a bitmap. This naturally lead to functions named grab_markup_from_filename() and render_text_onto_image() and others. The cleanest organization was one entry point named generate_png_from_markup_filename(). The entry point did its job, using nested functions to accomplish its task. There was no need for a class, because there was no object with state. My alternative was to create a module with private methods hiding my helpers, but it would be messier.
Second, I use nesting for closures. The most common example is for creating decorators. The trick is that I return a reference to an inner function, so that inner function and the outer parameter value are not garbage collected.
use it this way:
or, more concisely:
And yes, it should be hard to trace. Remember that “def” is just another statement.
So, here are two places nested classes are helpful. There are more. It is a tool.