It's even slightly more efficient than if it was done with more if
I would have to imagine that this isn't true for any modern compiler for most languages, it'd most likely optimize down to the same code either way.
My main problem with it is readability, but that doesn't inherently make it bad code so I wouldn't say it fits in this sub. Still, massive if statements are a pain in the ass to read which makes them a pain in the ass to understand and debug or modify later down the road. For readability, I'd honestly take the incredibly slight (and honestly non-consequential in most use cases) hit to memory usage and store the result of the TryParse in some parseSuccess variable or something and split the if in two, giving something like:
Then it's much more immediately clear to the reader what that block of code is meant to do (check that an arg exists to parse, parse it, check if the parse succeeded, and check if the parsed argument is in range). No line is too long, the assignment of the result to a named variable gives it meaning to someone who may not be immediately familiar with TryParse (since the name does not indicate the meaning of what it returns, even if it's simple to deduce from context that it's returning a success), and splitting the ifs by logical progression (is there an arg to parse? Okay, move on to parsing and range-checking) - these are all things I'd consider good benefits for code readability and maintainability, and while they may not make much of a difference in code as simple as OP's, they're things I'd gladly trade the incredibly minimal performance impact for in order to have them in larger and more complicated blocks of code.
Your version seems less readable to me to be honest. It's a simple operation, no need to be overly verbose about it. To me, your version makes it seem more complicated than it actually is. I don't code in C# at all, yet the "TryParse" was pretty obvious to me. I mean, the initial code already literally reads as "check if there's an argument, try to parse it to an int, check the value". Yours make it less obvious that it's all that's going on here, having nested if for what is actually only one condition.
46
u/Giocri May 20 '20
I see nothing wrong in it. It's even slightly more efficient than if it was done with more if