开发者

How can I make this method more general?

开发者 https://www.devze.com 2023-01-13 20:04 出处:网络
I have this method called LoadToDictionary. It accepts a dictionary and a filepath. Currently, it would look something like this:

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?


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:

  1. Don't take a dictionary of string to string; take a dictionary of, say, string to arbitrary type.

  2. Don't take a Dictionary<...>; take an IDictionary<...>.

  3. Don't take any kind of dictionary. Take an Action<K, V> whose action could be to enter the item in a dictionary.

  4. 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.

  5. 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:

static void MakeMap<T, K, V>(this IEnumerable<T> sequence, Action<K, V> mapWriter, Func<T, K> keyExtractor, Func<T, V> valueExtractor)
{
    foreach(var item in sequence)
        mapWriter(keyExtractor(item), valueExtractor(item));
}

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:

public static ILookup<TKey, TElement> ToLookup<TSource, TKey, TElement>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
Func<TSource, TElement> elementSelector,
IEqualityComparer<TKey> comparer) { ... }

And hey, we've just reinvented the ToLookup() extension method. Sometimes when you make a method general enough you discover that it already exists.


I see two actual questions here:
1) Can a Method Signature be dynamic, such that the types it expects can change?
2) Can a Method Body be dynamic, such that my logic can change on-the-fly.

I'm not sure how either of those two could be accomplished withoug using Reflection and a fair deal of code gen. I'm sure there are those here who are, though.

Depending on what you need, though, basic Method Overloading sounds like what you're actually looking for.

Using your example:

void LoadToDictionary(Dictionary<string, string> dict, string filePath)
{ ... code here ... }

//to have a LoadToDictionary method which accepts Dictionary<int, int>
void LoadToDictionary(Dictionary<int, int> dict, string filePath)

//To change the processing logic, you either need a new method name, 
// or to override the original in an inheriting class

void AlternateLoadToDictionary(Dictionary<string, string> dict, string filePath)
override void LoadToDictionary(Dictionary<string, string> dict, string filePath)

An even better alternative is to have your parsing logic separate from your Dictionary creation logic. You can even call the other method from inside your LoadDictionary method so normal overloading could work there, too

void LoadToDictionary(Dictionary<string, string> dict, string filePath)
{
    string[] fileLines;

    if([yourBaseLineCondition])
    fileLines = LoadDataFromFile(filePath, false);

    else fileLines = LoadDataFromFile(filePath, true); 
}

string[] LoadDataFromFile(string filePath, bool altLogic)
{
    if(altLogic) return LoadDataFromFileAlt(filePath)
    else
    { ... your logic ... }
}

string[] LoadDataFromFileAlt(string filePath)
{ ... your alt logic... }

Basic method overloading gives you a lot of flexability. More importantly, it allows you to follow the YAGNI principle without cutting off avenues for expansion. You can always come back into your code and ADD the LoadToDictionary<myCustomObject, myCustomObject> method if you need to do so.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号