Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I violate the S in SOLID or should I violate the DRY Principle?

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.

like image 731
B. Clay Shannon-B. Crow Raven Avatar asked Jan 12 '23 06:01

B. Clay Shannon-B. Crow Raven


1 Answers

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.

like image 150
goric Avatar answered Jan 27 '23 10:01

goric