Answer the question
In order to leave comments, you need to log in
Method overloading without code duplication in C#?
Good afternoon,
different overloads of the method do almost the same thing, depending on the presence of some arguments. That is, there can be 10 arguments, or maybe 8. Accordingly, 2 overloads. But the code for working on these arguments is 80% the same. The rest can be split into if. Moreover, the code is not small - queries to the database, calculations, writing to the database, return, etc. 40 lines.
What do you do in this case? Duplicate code for different overloads? Do you break the internals of the method into separate methods and take them out separately, referring to them in each of the overloads? So you can also spawn long chains of calls.
Thanks in advance!
Answer the question
In order to leave comments, you need to log in
In cases where the code allows it, you can move the main functionality into one of the methods (basic for you) and call it from other overloads:
string GenerateText(string text)
{
return GenerateText(text, "Без заголовка");
}
string GenerateText(string title, string text)
{
return title + Environment.NewLine + text;
}
string GenerateText(string title, string text = "Без заголовка")
{
return title + Environment.NewLine + text;
}
string GenerateText(string title, string text)
{
return title + Environment.NewLine + (text ?? "Без заголовка");
}
string GenerateText(string title, params string[] text)
{
return title + Environment.NewLine + string.Join(Environment.NewLine, text);
}
What do you do in this case? ... Break the internals of the method into separate methods and take them out separately, referring to them in each of the overloads?
I select the general functionality in a separate method. I call methods from each other. There are also default settings.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question