I have this method called LoadToDictionary. It accepts a dictionary and a filepath. Currently, it would look something like this:
void LoadToDictionary(Dictionary<string, string> dict, string filePath. Then inside, it would have a lot of code to extract the contents of the file in filePath to a dictionary. I want to make it more general, so it could, say, take a dictionary with int’s instead, and the ability to change the parsing code in the method. Should I mark this method and later override it? Is there any other way?
I have this method called LoadToDictionary. It accepts a dictionary and a filepath. Currently,
Share
Premature generality gives premature optimization a run for the money as the root of evil. Generality is expensive and expensive code should be justified by clear benefits.
I would therefore drive increased generality into your method on the basis of specific scenarios. I can think of many ways to make your method more general:
Don’t take a dictionary of string to string; take a dictionary of, say, string to arbitrary type.
Don’t take a
Dictionary<...>; take anIDictionary<...>.Don’t take any kind of dictionary. Take an
Action<K, V>whose action could be to enter the item in a dictionary.Don’t take a filename. You’re just going to turn the file name into a stream anyway, so take a Stream to begin with. Have the caller open the stream for you.
Don’t take a Stream. You’re just going to turn the stream into a sequence of items anyway, so take an
IEnumerable<...>and have the caller parse the stream for you.How general can we make this? Let’s suppose we have a sequence of T which is then transformed into a map from K to V. What do we need? A sequence, a key extractor, a value extractor, and a map writer:
Notice how the code gets really short when it gets really general. That is pretty freakin’ general, and as a result the call site will now look like an unholy mess. Is that really what you want? Are you going to use all that generality effectively? Probably not. What are the scenarios you actually have that are driving a desire to be more general? Use those specific scenarios to motivate your refactoring.
Is that as far as we can go? Could we get even more general than this? Sure. We could notice for example that it seems bad to have a side effect in there. Shouldn’t the method just be returning a newly constructed dictionary? What should the comparison policy of that dictionary be? What if there is more than one item that has the same key? Should it be replaced, or should we have the dictionary actually be a map from keys to a list of values? We could take these ideas and make a new method that solves all those problems:
And hey, we’ve just reinvented the ToLookup() extension method. Sometimes when you make a method general enough you discover that it already exists.