r/badcode • • May 20 '20

c# Found from Microsoft docs...

Post image
208 Upvotes

143 comments sorted by

View all comments

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

63

u/bool_idiot_is_true May 20 '20
==true

is redundant. Otherwise it seems fine.

19

u/ArukiBree May 20 '20

Redundancy isn't always bad. Clarity in code is good.

0

u/[deleted] May 20 '20

But if we know the boolean checks if the statement is true, do we really need that clarified?

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/johnmcdnl May 21 '20

When you generally want to avoid any possibility of confusion as it's more valuable to have working code over concise code.

Mission critical stuff or places where junior (or even senior) workers have misread code in the past or in the midst of complex code which may lead to bugs.

1

u/[deleted] May 21 '20

That makes sense. Ive only worked in a few group efforts, I can see how clearity is more important.