I’m refactoring some code and I have written a method that modifies a Dictionary and returns it. Is this a better practice than using an out parameter? I don’t really want to create an extension method in this case because it would add the method to the Dictionary class which is overkill for what this is used for. Please don’t point out that I shouldn’t be using dynamic sql, that is another stage in the refactoring that currently has to be deferred.
private static Dictionary<int, string>
FindMatches(Dictionary<int, string> records,
string queryFormat,
string region,
string type,
string label)
{
var query = string.Format(queryFormat, SqlSvrName, SqlDbName, SqlSchemaName,
region, type, label);
using (var dr = DataRepository.Provider.ExecuteReader(CommandType.Text, query))
{
if (dr != null && !dr.IsClosed)
{
while (dr.Read())
{
var assetID = (int)dr.GetDouble(0);
if (!records.ContainsKey(assetID))
records[assetID] = dr.GetString(1);
}
}
}
return records;
}
Edit: I was a bit hasty with my use of the term out above. I’m trying to make it explicit in my code that the dictionary is modified by the method. An out parameter here would only make sense if the method created a new dictionary and returned it via that parameter. A little more context for this is that the method is called multiple times with different query strings and the dictionary may already contain matches.
Edit2: Just to follow up I removed the records parameter and instead return a list of KeyValuePair from FindMatches. I end up with a List<KeyValuePair<int, string>> which I convert to a dictionary via:
records
.GroupBy(rec => rec.Key)
.ToDictionary(grp => grp.Key, grp => grp.First().Value);
Why should your method modify an existing dictionary at all? It doesn’t seem to use the existing keys/values, so make this method just return a new
Dictionary<string, int>:You can then also write a separate method to merge two dictionaries in a particular way – or return a new dictionary which is the result of merging two existing ones.. Separate the two concerns.