Question

I had a method for sending GET requests like this:

private JArray GetRESTData(string uri)
{
    try
    {
        var webRequest = (HttpWebRequest)WebRequest.Create(uri);
        var webResponse = (HttpWebResponse)webRequest.GetResponse();
        var reader = new StreamReader(webResponse.GetResponseStream());
        string s = reader.ReadToEnd();
        return JsonConvert.DeserializeObject<JArray>(s);
    }
    catch // This method crashes if only one json "record" is found - try this:
    {
        try
        {
            MessageBox.Show(GetScalarVal(uri));
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
    return null;
}

...I altered it to deal with POST requests by wedging this between the assignments to webRequest and webResponse:

if (uri.ToUpper().Contains("POST"))
{
    webRequest.Method = "POST";
    webRequest.ContentLength = 0;
}

...and renamed it GetOrPostRESTData()

But that violates the Single Responsibility Principle.

Yet, if I make it into two methods, with the POST method the same as the GET method, with the exception of the additional two lines of code that are otherwise in the conditional ("if Post"), I am violating DRY, as most of the code is the same.

Is there a third way? A middle way? Or must I choose between these two violations? I am stuck between a DRY and a SOLID place.

Was it helpful?

Solution

How about looking at it from a higher level of abstraction? Instead of worrying about whether it's a GET or POST in the method name, just call it something like ProcessRequest. In that case, you could argue that the SRP is still being followed - the single thing your method is doing is processing the request indicated in the given URI - and you aren't duplicating any code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top