Let’s 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 can’t be the correct solution.

Cody’s company outsourced this problem, and they got back a solution that is obviously much better.

    public static decimal? GetPosition(string endpointId, ICollection<UserGeoPositionModel> 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. That’s reusability! And you don’t 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);

That’s 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.

[Advertisement] Infrastructure as Code built from the start with first-class Windows functionality and an intuitive, visual user interface. Download Otter today!