Cutting Down On The Number Of Enums _AND_ Improve Readability
Posted on August 21, 2008Tobin gave me an idea in his comment on my Enum versus Boolean post.
In the asp.net mvc framework, there are few method signatures that take an object parameter like this:
string Html.ActionLink(string linkText, string actionName, string controllerName, object values)
| |
1
|
In the source, the devs either have TODO comments indicating that they need to use TypeDescriptor for determining properties, or they are using the TypeDescriptor. A little digging got me this post and I put it on my delicious todo list. So now it all makes sense. I'm sure there is a cleaner way to do this but here's an overload I added to OrderBy:
public IEnumerable<TModel> OrderBy(object values) {
if (values == null) throw new ArgumentNullException("values");
string propertyName = String.Empty;
Sort sortDirection = Sort.Ascending;
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(values);
foreach (PropertyDescriptor prop in props) {
switch (prop.Name) {
case "Property":
propertyName = prop.GetValue(values).ToString();
break;
case "SortAscending":
sortDirection = Convert.ToBoolean(prop.GetValue(values)) ? Sort.Ascending : Sort.Descending;
break;
}
}
return OrderBy(propertyName, sortDirection);
}
| |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
There's prolly something I can do about the switch statement, I just scratched out the method this morning. But now checkout the usage:
repo.OrderBy(new { Property = "FirstName", SortAscending = true });
| |
1
|
Now reading the code *usage* is easier and there are no enums. The only problem is that now you have to make sure and document the possible values for that object parameter, cuz using an api that has a parameter of type object can be a little confusing unless you know what's supposed to go in there.