This is something that\'s been bugging me for a bit now. In some cases you see c
ID: 644856 • Letter: T
Question
This is something that's been bugging me for a bit now. In some cases you see code that is a series of overloads, but when you look at the actual implementation you realize they do logically different things. However writing them as overloads allows the caller to ignore this and get the same end result. But would it be more sound to name the methods more explicitly then to write them as overloads?
public void LoadWords(string filePath)
{
var lines = File.ReadAllLines(filePath).ToList();
LoadWords(lines);
}
public void LoadWords(IEnumerable<string> words)
{
// loads words into a List<string> based on some filters
}
Would these methods better serve future developers to be named as LoadWordsFromFile() and LoadWordsFromEnumerable()? It seems unnecessary to me, but if that is better what programming principle would apply here?
On the flip side it'd make it so you didn't need to read the signatures to see exactly how you can load the words, which as Uncle Bob says would be a double take. But in general is this type of overloading to be avoided then?
Explanation / Answer
I really wonder why the version with actual IO has been added to the class in the first place. What's the point here? How is that the responsibility of the class?
Why not add a method to load the words from a zipped file, or from an .xml or a .json or a .doc or an SQL database or over http or ftp or whatever? Because it's not the responsibility of the class, that's why!
Particularly the file name based method adds a dependency against a global object. Which is anything but ideal if you ask me.
So I would argue that the programming principle that would apply here is composition.
loader.LoadWords(someList)
loader.LoadWords(File.ReadAllLines(somePath).ToList())
loader.LoadWords(Http.get(someUrl).split(NEWLINE))
...
Tying together a particular method of loading the data and a particular method of processing it should not be done in the class itself, but in another module, whose responsibility it is to carry out just that composition. Could be an IoC container or something, but it doesn't have to be as fancy as that.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.