CodeSOD: Location Not Found |
Lets say you have a collection of objects which contain geographic points. You want to find a specific item in that collection, and then extract the lat/lon of that item. You might write code like:
var point = userGeoPositions.Where(x => x.userId = userId);
decimal lat = point.Latitude;
decimal lon = point.Longitude;
Of course, this means writing getters and setters for the Latitude and Longitude properties; getters/setters are somewhat repetitive, and repetitive code is a code smell, so obviously, this cant be the correct solution.
Codys company outsourced this problem, and they got back a solution that is obviously much better.
public static decimal? GetPosition(string endpointId, ICollection userGeoPositions, bool isLatitude)
{
var position = userGeoPositions.FirstOrDefault(x => endpointId.Contains(x.UserID));
return position != null
? (decimal?)Convert.ToDecimal(isLatitude ? position.GeoLatitude : position.GeoLongitude)
: null;
}
Instead of writing separate getters for each property, this is one function that can get either property. Thats reusability! And you dont even have to filter the collection before you call this function! Now, when you want the lat/lon of a point, you simply write:
decimal lat = GetPosition(endpointId, geoPositions, true);
decimal lon = GetPosition(endpointId, geoPositions, false);
Thats one fewer lines of code than my initial solution. Now, since this function filters on each call, getting the latitude and longitude requires two searches through the whole list, but hey- CPU time is cheap. Programmer time is expensive.
| Комментировать | « Пред. запись — К дневнику — След. запись » | Страницы: [1] [Новые] |