July 20, 2011, 1:44 a.m.
posted by tekkero
Calling a method recursively or implementing the method using recursion refers to the fact that the method calls back on itself. This is sometimes the simplest way to implement a method. Listing 4.15 counts the lines of all the C# source files (*.cs) in a directory and its subdirectory.
Returning All the Filenames, Given a Directory
The program begins by passing the first command-line argument to DirectoryCountLines(), or by using the current directory if no argument was provided. This method first iterates through all the files in the current directory and totals the source code lines for each file. After each file in the directory, the code processes each subdirectory by passing the subdirectory back into the DirectoryCountLines() method, rerunning the method using the subdirectory. The same process is repeated recursively through each subdirectory until no more directories remain to process.
Readers unfamiliar with recursion may find it cumbersome at first. Regardless, it is often the simplest pattern to code, especially with hierarchical type data such as the filesystem. However, although it may be the most readable, it is generally not the fastest implementation. If performance becomes an issue, then developers should seek an alternate solution in place of a recursive implementation. The choice generally hinges on balancing readability with performance.