Refactor to smaller function, how?

105 Views Asked by At

I have a function that loads a large selectlist for ASP.NET MVC. This functions has a methodsize of 354 rows. I want to refactor to more functions or to a local field so that each function will be less than 40 lines.

Here is the code snippet:

public static SelectList CreateShutterSpeedList()
        {
            var shutterSpeedList = new List<CameraSettingItem>();

            var secNotationPostfix = "\"";

            shutterSpeedList.Add(new CameraSettingItem
            {
                Id = ShutterSpeedDefaultValue,
                Description = string.Empty
            });

            shutterSpeedList.Add(new CameraSettingItem
            {
                Id = 1,
                Description = "30" + secNotationPostfix
            });

etc

Maybe a private list as a variable ? Or loading from file ? Or else...?

2

There are 2 best solutions below

2
On BEST ANSWER

If IDs above ShutterSpeedDefaultValue are assigned sequentially, you could create an array of descriptions first, and then convert it to CameraSettingItem list with LINQ:

var descriptions = new[] {
    string.Empty
,   "30" + secNotationPostfix
,   ...
};
shutterSpeedList = descriptions
    .Select((d,i) => new CameraSettingItem {
        Id = i==0 ? ShutterSpeedDefaultValue : i
    ,   Description = d
    })
    .ToList();

You could also create a list of CameraSettingItems outside of your method's body, like this:

private const string secNotationPostfix = "\"";

private static IList<CameraSettingItem> shutterSpeedList = new List<CameraSettingItem> {
    new CameraSettingItem {
        Id = ShutterSpeedDefaultValue,
        Description = string.Empty
    },
    new CameraSettingItem {
        Id = 1,
        Description = "30" + secNotationPostfix
    },
    ...
};

public static SelectList CreateShutterSpeedList() {
    return new SelectList(shutterSpeedList, "Id", "Description");
}
0
On

You can store items that you need in JSON or XML files and deserialize them when you need using JavaScriptSerializer or Json.NET for example:

public static SelectList CreateShutterSpeedList(
{
    var json = File.ReadAllText(@"\ShutterSpeedList.json");
    var shutterSpeedList = JsonConvert.DeserializeObject<List<CameraSettingItem>>(json);
    // Convert shutterSpeedList to SelectList and return
}

Alternatively you can reduce number of lines by using collection initializer (as @dasblinkenlight pointed out) and constructors with optional parameters/object initializers if you have access to CameraSettingItem code:

public static SelectList CreateShutterSpeedList()
{
    var secNotationPostfix = "\"";    
    var shutterSpeedList = new List<CameraSettingItem>
    {
        new CameraSettingItem(id: ShutterSpeedDefaultValue),
        new CameraSettingItem(id: 1, description: "30" + secNotationPostfix),
        ...
    };
    // Convert shutterSpeedList to SelectList and return
}