I've always been told "never use goto, there's always a better way" and for the longest time I just accepted it. Lately though, I've been running into such scenarios in which I have to repeat this bit of code every time I return early.
I personally hate repeating myself, even the littlest bit of code. So I ask, Is this use of goto really that bad? It prevents me from having to write that bit of code 3 times and sure, theoretically I could write some guard clauses (that could be combined into a single guard clause) that prevents the need for the try/catch and therefore having a single place for that bit of code, but would that actually be more readable?
public static IQueryable<T> Sort<T>(this IQueryable<T> query, String field, String direction, Expression<Func<T, Int32?>> defaultSort = null)
{
if (String.IsNullOrWhiteSpace(field)) { goto FAILED; }
try
{
// Dynamic LINQ - Field: "SomeProperty.OptionalProperty", Direction: "Desc" or "Asc"
query = query.OrderBy(String.Format("{0} {1}", field, direction));
}
// NOT FOUND: Field wasn't found just return the original query.
catch (NullReferenceException)
{
goto FAILED;
}
// NOT FOUND: Field wasn't found just return the original query.
catch (ParseException)
{
goto FAILED;
}
return query;
// SOMETHING FAILED: Return the original query with the optionally supplied default sort.
FAILED:
if (defaultSort != null)
{
query = query.OrderBy(defaultSort);
}
return query;
}
goto fail
bug/security flaw. Granted, the problem was really caused by missing braces and likely a bad merge. But still,goto fail
is almost what you wrote here :) \$\endgroup\$goto fail
/goto FAILED
was funny \$\endgroup\$OrderBy
? This is not the BCL version of it. \$\endgroup\$