mardi 22 juin 2021

How do I apply DRY principle?

I want to clean up my class that does web requests to the server. The problem that I ran into is a lot of my code is just repeating it self but each time with a little modification. For example almost the whole method looks the same except one is POST and the other is PATCH or GET request.

            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(req);
            httpWebRequest.Headers["Authorization"] = "Basic " + auth;
            httpWebRequest.Method = "POST";
            httpWebRequest.ContentType = "application/json";
            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                string json = new JavaScriptSerializer().Serialize(new
                {
                    body = GetStringFromFile()
                }) ; 

                streamWriter.Write(json);
            }
            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(req);
            httpWebRequest.Headers["Authorization"] = "Basic " + auth;
            httpWebRequest.Method = "GET";
            httpWebRequest.ContentType = "application/json";

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

This is basically how my whole class looks like and I don't think it should look like that. I don't know if I should be extracting the already simple request to make it smaller and put it in another method, and do that for each type of request(post,get,patch). Or maybe just keep doing this even tho it looks wrong to me because it's repeating code that I don't know how to deal with. What would be the best solution in this case?

Aucun commentaire:

Enregistrer un commentaire