HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Scanning a .cs file or a directory

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
filedirectoryscanning

Problem

This is a console application which takes as an argument either a .cs file or a directory. If it's a .cs file, it scans it; if it's a directory, it scans all .cs files within the directory.

A simplified view of a method which chooses whether it's a file or a directory and reports errors is this one:

public static void ProcessPath(string path)
{
    if (path.EndsWith(".cs"))
    {
        if (File.Exists(path))
        {
            Program.ScanFile(path);
        }
        else
        {
            Console.WriteLine("The specified file doesn't exist.");
            Environment.Exit(1);
        }
    }
    else
    {
        if (Directory.Exists(path))
        {
            Program.ScanDirectory(path);
        }
        else
        {
            if (File.Exists(path))
            {
                Console.WriteLine("The path corresponds to a file, but only *.cs files are supported.");
            }
            else
            {
                Console.WriteLine("The specified directory doesn't exist.");
            }

            Environment.Exit(1);
        }
    }
}


How can I rewrite the if/else logic in a more elegant way? Would it improve readability?

Solution

In my opinion, the easiest way would be to embrace exceptions. DirectoryNotFoundException and FileNotFoundException are there for a reason, and actually even calling .Exists might not save you from them - the file might be moved/removed between the Exists and the action you're taking next.

You can do:

public static void ProcessPath(string path)
{
    var extension = Path.GetExtension(path);

    if(string.IsNullOrEmpty(extension))
    {
        Program.ScanDirectory(path);
    }
    else
    {
        if(extension != ".cs")
            throw new NotSupportedException("Only .cs files are supported");

        Program.ScanFile(path);
    }
}


And either catch those exceptions higher up and write them to console or (considering you're doing Environment.Exit in your example), just let them propagate and crash the application.

Code Snippets

public static void ProcessPath(string path)
{
    var extension = Path.GetExtension(path);

    if(string.IsNullOrEmpty(extension))
    {
        Program.ScanDirectory(path);
    }
    else
    {
        if(extension != ".cs")
            throw new NotSupportedException("Only .cs files are supported");

        Program.ScanFile(path);
    }
}

Context

StackExchange Code Review Q#36335, answer score: 13

Revisions (0)

No revisions yet.