Article 6DQCC CodeSOD: A Piece of Switch

CodeSOD: A Piece of Switch

by
Remy Porter
from The Daily WTF on (#6DQCC)

Functional programming is fine. It's a different way of thinking about programs, but it makes some problems very easy to describe. It's a tool that belongs in the toolbox, and you should use the right tool for the job.

LH's co-worker doesn't quite take that approach. Their solution to pretty much every problem is to use lambdas, and the functional switch expression in C#. But, when combined with their coding style, it creates some... interesting code.

public bool IsSuccessCode => 299 >= (int)StatusCode && (int)StatusCode >= 200 &&Response switch{ResultMessage rm => rm.ResultMessageCode == ResultMessageCode.Done,_ => throw new NotImplementedException()};

This is a C# "expression body definition". It initializes the member property IsSuccessCode using a lambda. The => operator is what marks this as a lambda. And then our eyes get visually confused, because the rest of the lambda depends on a series of >= operators, which aren't the same thing, but when you're scanning code, certainly look alike.

The fist two clauses of the lambda are, based on the magic numbers encoded here, checking to ensure that an HTTP status code is in the range of successful status codes. Which is awkward but fine, and then we get to the switch.

This is a functional, matching version of the switch. Response, in this context, must be another property. In this case, if Response can be cast to a ResultMessage, then we return rm.ResultMessageCode == ResultMessageCode.Done. Failing that, we throw an exception.

So, the property is at least vaguely clear about its name: if it's a successful HTTP response and the message code is "done", then we consider this success. But the aggressive use of functional paradigms and type casting in the switch left me spending a solid few minutes trying to understand what it was doing- some of those syntax conventions didn't even look correct.

But mostly, I'm posting this because my eyes still get thrown off by the => and the >= and I end up thinking I'm looking at nested lambda expressions and get really confused.

The logic is fine, the expression is needlessly cryptic.

proget-icon.png [Advertisement] Keep the plebs out of prod. Restrict NuGet feed privileges with ProGet. Learn more.
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments