tags:

views:

35

answers:

2

I am currently writing some methods to determine certain paths on the hard drive. For the sake of the example, let's call them GetBasePath(), GetSpecialPath(), etc.

My question is, from a design point of view, how should these methods behave if the directories do not exist in the expected location? I am a bit puzzled what the best practice might be in this case.

Some contradicting possible solutions that I considered:

1: The name of the method should tell you what it does, therefore GetBasePath or GetSpecialPath do not imply that the method checks for existence. It's the caller's business to check for existence himself. Also, a method called GetBasePathIfItExists would be a bit over the top...

2: If the paths do not exist, that is an exceptional case, because they are expected to exist (at least in my case), therefore the methods should throw exceptions.

3: The methods should only return VALID paths, therefore if it cannot return a valid existing path, an empty string should be returned. (E.g.: Microsoft does this for Environment.GetFolderPath())

I am currently favoring solution 1, as this has the advantage that you can easily tell the user WHERE the path is expected to exist. An exception could tell you the same, but is it really an exceptional case?

What would you suggest?

I hope this question is not too specific and other readers can benifit from a good answer as well.

+1  A: 

Another option might be to have the functions create the corresponding directory if it doesn't already exist. Of course the ability to do this depends on the expected permissions of the calling application and the directory location. If the directory can't be created (for example, if a file of the same name already exists there), then throw an exception.

Greg Hewgill
+1  A: 

If these paths are expected to always exist, then their non existence is exceptional and you should indeed throw an exception. This is also how the framework operates in many of the IO namespace classes.

If there is a reasonable expectation that these paths may not exist, you may want to provide an xxxExists boolean method that will check for existence and allow the programmer to do something about the issue.

Oded