
Beman Dawes wrote:
How should size( "foo" ) behave if "foo" is a directory?
1) Throw. The function should be renamed file_size().
2) Return 0. Directories don't strictly speaking have a size.
3) Return the number of entries in the directory. Directories are really just containers; so of course they have a size.
(1) and (3) seem most attractive to me; (2) seems useless for directories, and probably misleading.
The problem with (3) is that for many (most?) operating systems the implementation would have to iterate over the directory to get a count, and this difference in complexity compared to getting the size of a file (which is usually constant complexity) could be pretty surprising.
I'm inclined to go with (1), naming the function "file_size", and then add a function later to get the number of entries in a directory. But only if there is enough demand. I don't want to clutter up the library with a lot of seldom used functions that can be trivially written as user code.
Thoughts?
I agree with your conclusion. Asking for the file_size of a directory is just wrong. One should throw exceptions when a member function is used on an object which is not applicable to the actual type or state of the object. That way it is clearest that the call is incorrect. Anything else masks the incorrectness of the call and one does not want to do that.