Where should I put a function that is called many times?
This is a follow-up to this question How to avoid repeated code?
I am using ASP.NET 4.0 with C# and I have a function called FillDropDownList(DropDownList ddl, DataTable dt, string dataValueField, string dataTextField, string defValue)
which is called multiple times on one of my ASP.NET pages to populate 开发者_StackOverflow中文版some dropdown lists. I am now finding that I have several pages where I need to populate several dropdownlists in exactly the same way.
Rather than copying and pasting the same code in different pages, should I create a new class and put the method in that new class? How would I call it? What should I call the class? Should it have other functions in it? I was thinking maybe I should call it Util
? What would you do?
You can create static class and place there your function
public static class DropDownFiller
{
public static void FillDropDownList(DropDownList ddl, DataTable dt, string dataValueField, string dataTextField, string defValue)
{
/// bla bla
}
}
Or you can create an extension to DropDownList (it is also a static class)
public static class DropDownListExtension
{
public static void FillDropDownList(this DropDownList ddl, DataTable dt, string dataValueField, string dataTextField, string defValue)
{
/// bla bla
}
}
Usage (like method of DropDownList)
yourDropDownList.FillDropDownList(dataTable,valueField,textField,defValue);
精彩评论