Refactoring: minimizing if-statements

den 1 juni 2017 av Dennie

Multiple if-statements with null checks which returns a formatted result is quite common and I often write that kind of code myself. Imagine we add a zip code and a country (yes, I know, returning only the zip code wouldn't be that great. But you get the point, right? just keep imagine) and the code will be slightly harder to read and understand.

Before:

private string CreateLocation(Event event) {
    if (event.ConfirmedAddress) {
        if (!string.IsNullOrWhiteSpace(event.AddressName) && !string.IsNullOrWhiteSpace(event.City))
        {
            return $"{event.AddressName}, {event.City}";
        }
        if (!string.IsNullOrWhiteSpace(event.AddressName))
        {
            return event.AddressName;
        }
        if (!string.IsNullOrWhiteSpace(event.City))
        {
            return event.City;
        }
    }
    return "Location is not confirmed yet.";
}

 After:

private string CreateLocation(Event event) {
    if (event.ConfirmedAddress) {
        var location = new [] {event.AddressName, event.City}
        	.Where(x => !string.IsNullOrWhiteSpace(x));

        return string.Join(", ", location);
    }
    return "Location is not confirmed yet.";
}