6
\$\begingroup\$

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?

\$\endgroup\$

1 Answer 1

13
\$\begingroup\$

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.

\$\endgroup\$
3
  • 2
    \$\begingroup\$ +1 for exceptions. The notion of being able to code defensively against file system objects is a fallacy. There are absolutely no guarantees with the file system. \$\endgroup\$
    – MattDavey
    Nov 29, 2013 at 9:27
  • 2
    \$\begingroup\$ What if I want to scan the directory ".sharpDevelopProjects" or "backup 29.11.2013"? \$\endgroup\$ Nov 29, 2013 at 10:28
  • 1
    \$\begingroup\$ @abuzittingillifirca Then the GetExtension fails, but you have no real way of distinguishing those cases unless you try to get the attributes from the filesystem. \$\endgroup\$ Nov 29, 2013 at 12:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.