Дублирование кода, удобочитаемость кода и удобство сопровождения кода - PullRequest
0 голосов
/ 16 января 2019

У меня здесь очень общий вопрос. Я всегда смущен комментариями обзора кода удаления дублирования кода. Давайте возьмем следующий пример:

                public static void RunFunction1(TraceWriter log)
                {
                    ITelemetryLogger appinsights = new ApplicationInsightLogger(INSTRUMENTATIONKEY);
                    DateTime startTime = DateTime.Now;
                    log.Info($"RunAudit Job is triggered at {startTime}");
                    IRestClient client = new RestClient();
                    client.BaseUrl = SERVICE_BASEURL;
                    IRestResponse response = client.Execute(new RestRequest("API/RunFunction1", Method.POST));
                    if (response.IsSuccessful)
                    {
                        DateTime endTime = DateTime.Now;
                        log.Info($"RunFunction1 Job completed successfully at {endTime}, Time of Execution is {endTime - startTime}");
                    }
                    else
                    {
                        log.Error($"RunFunction1 Job Failed with message {response.Content.ToString()} and Status Code {response.StatusCode}");
                        Dictionary<string, string> properties = new Dictionary<string, string>();
                        properties.Add("MethodName", "FunctionRunFunction1");
                        properties.Add("ErrorMessage", $"RunFunction1 Job Failed with message {response.Content.ToString()} and Status Code {response.StatusCode}");
                        appinsights.LogError("ScheduledJobFailed", properties);
                    }
                }



                public static void RunFunction2(TraceWriter log)
                {
                    ITelemetryLogger appinsights = new ApplicationInsightLogger(INSTRUMENTATIONKEY);
                    DateTime startTime = DateTime.Now;
                    log.Info($"RunAudit Job is triggered at {startTime}");
                    IRestClient client = new RestClient();
                    client.BaseUrl = SERVICE_BASEURL;
                    IRestResponse response = client.Execute(new RestRequest("API/RunFunction1", Method.POST));
                    if (response.IsSuccessful)
                    {
                        DateTime endTime = DateTime.Now;
                        log.Info($"RunFunction2 Job completed successfully at {endTime}, Time of Execution is {endTime - startTime}");
                    }
                    else
                    {
                        log.Error($"RunFunction2 Job Failed with message {response.Content.ToString()} and Status Code {response.StatusCode}");
                        Dictionary<string, string> properties = new Dictionary<string, string>();
                        properties.Add("MethodName", "FunctionRunFunction2");
                        properties.Add("ErrorMessage", $"RunFunction2 Job Failed with message {response.Content.ToString()} and Status Code {response.StatusCode}");
                        appinsights.LogError("ScheduledJobFailed", properties);
                    }
                }

Теперь, мой вопрос, если вы видите, что в обеих функциях есть дублированный код. Мы можем переместить этот код в одну общую функцию, которая может заботиться об общем коде. Но у меня вопрос: не связываем ли мы обе логики функций друг с другом, заставляя их вызывать общую функцию? 1.) Что такое тонкая грань между дублированием кода, читаемостью кода и удобством сопровождения кода?

2.) Есть ли какие-либо рекомендации, которым кто-то может следовать?

3.) Каким лучшим практикам следует следовать?

...