Imagine there is a simple method like this:
public async Task<ValidatePhoneNumberResult> ValidatePhoneNumberAsync(
string phone_number,
string country_code,
string country_iso,
DeviceUuid device_uuid, // DeviceUuid supports his own ToString();
string os_name,
string os_version,
string model,
string screen_resolution,
string sim_operator = "00000",
string is_usim = null
)
{
Uri uri = new Uri(MY_URI);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uri);
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("phone_number", phone_number.ToString());
dic.Add("country_code", country_code.ToString());
dic.Add("country_iso", country_iso.ToString());
dic.Add("os_name", os_name.ToString());
dic.Add("model", model.ToString());
dic.Add("screen_resolution", screen_resolution.ToString());
dic.Add("sim_operator", sim_operator.ToString());
if (is_usim != null)
{
dic.Add("is_usim", is_usim.ToString());
}
request.Content = new FormUrlEncodedContent(dic);
return await GetResult<ValidatePhoneNumberResult>(request);
}
This is my first design. I will make a lot of functions like that from now. But the code has something I don't like. It is the part of adding parameters to a dictionary. I think it is obvious code duplication.
- All parameter names are used as the dictionary's keys.
- And they all will implement their own ToString() method.
- If parameter is
null
, it shouldn't be put in dictionary.
It would be better, if it could:
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("phone_number", phone_number.ToString());
dic.Add("country_code", country_code.ToString());
dic.Add("country_iso", country_iso.ToString());
dic.Add("os_name", os_name.ToString());
dic.Add("model", model.ToString());
dic.Add("screen_resolution", screen_resolution.ToString());
dic.Add("sim_operator", sim_operator.ToString());
if (is_usim != null)
{
dic.Add("is_usim", is_usim.ToString());
}
// To
var dic = ExtractParametersAndMakeItAsDictionary();
How to make this code using C#(5.0) syntax? If you have a better suggestion, I will be happy to hear.
If it is impossible, is that possible wrapping it with macro
?(as we often did when we write C
)
Tell me any possible idea to deduplicate the code :)