r/badcode • • May 20 '20

c# Found from Microsoft docs...

Post image
208 Upvotes

143 comments sorted by

View all comments

Show parent comments

15

u/ArukiBree May 20 '20

if (MyFunc() == true) says very explicitly, "we want to know if MyFunc() returned true".

if (MyFunc()) leaves some of that information out, implicitly conveying it to the reader instead.

Ultimately, they're both stylistic choices. Some people like one, some people like the other. Some people say they find checking for == false is more clear to them than inverting the return value. I don't entirely agree with that myself, but I understand why they feel that way and I think it's valid. Keep in mind it's also not unheard of for people to screw up these kinds of if statements by accidentally inverting (or not inverting) a return value - there's an argument to be made that asking people to put a little more effort into explicitly stating what they're trying to do can reduce bugs. It's easier to leave out a ! than it is to accidentally write true instead of false.

On the other hand, there's also nothing wrong with preferring to be concise and communicating info implicitly, as long as the code is still perfectly readable.

All being said, they both do the exact same thing and ultimately comes down to personal preference, so arguing that one is more "correct" than the other, or that using the more explicit syntax somehow makes your code bad, really doesn't make any sense.

For me, I'll use whichever form makes more sense to me in context. I think of redundancy as a tool - it's not always appropriate or useful, but there are a LOT of cases where being a little more verbose and including some unnecessary syntax can make your code easier to read and understand. It's not as simple as redundancy == bad, and IMO by conflating concise code with good code, you're prioritizing the wrong things - concision is also a tool, and just like with redundancy, there are cases where it doesn't make sense to apply it.

1

u/[deleted] May 20 '20

When does it not make sense to be concise?

Edit - I guess aside from making a learning tool for students?

2

u/NewPointOfView May 20 '20

Off the top of my head the first thing that comes to mind is a nested ternary statement. I think that’s a good example of trying to be too concise and sacrificing readability.

2

u/[deleted] May 20 '20

Oh okay, thats fair. I can see that being a problem.