Im trying to think of the cleanest way to implement a couple
I\'m trying to think of the cleanest way to implement a couple of methods that open a file.
Consider the following method signatures:
public static DomainObject Load(Uri urlToFile)
{
/* downloads file and calls Load(savedToFilename) */
}
public static DomainObject Load(string filename)
{
/* creates filestream and calls Load(stream) */
}
public static DomainObject Load(Stream stream)
{
/* does actual loading */
}
I\'m trying to implement some concepts from Clean Code, specifically:
When constructors are overloaded, use static factory methods with names that describe the arguments. For example,
Complex fulcrumPoint = Complex.FromRealNumber(23.0);
is generally better than
Complex fulcrumPoint = new Complex(23.0);
Now, I know I do not have overloaded constructors, per se (I refactored away from that), but I think the principle is the same. So that implies that my Load methods be refactored to something like:
public static DomainObject FromURI(Uri urlToFile);
public static DomainObject FromFile(string filename);
public static DomainObject FromStream(Stream stream);
But, tbh, I think it\'s more intuitive to use what I\'ve already got. From a consumer\'s perspective it feels like Open will take whatever source I happen to have whereas the other method requires me to think first about what my source is and then wonder if there is a specific method for that.
So I ask, from your more experienced viewpoint, which is better and why?
Solution
I think \"Load\" is the way to go for a few reasons:
The parameter type is already in the parameter list- why specify it again in the method name?
If you happen to have multiple methods that produce something a stream in a class, \"FromStream\" becomes a problem.
In the age of intellisense, it\'s much more logical to type \"Load\" and get a list of possible parameter options, rather than look at three different methods (especially if more methods than just those in this set happen to start with \"From\").
Another decent rule of thumb is \"name methods after verbs when you can,\" which votes in favor of something akin to \"Load,\" or at least \"LoadFrom...\"