r/badcode • • Dec 20 '20

c# Was looking through my code and found this.

Post image
697 Upvotes

86 comments sorted by

35

u/Beach-Devil i++++; Dec 20 '20

(I don’t know C# and please correct me if I’m wrong) Can’t ints be implicitly casted to bools?

48

u/[deleted] Dec 20 '20 edited Dec 20 '20

In C++, yes, but sadly not in c#, which is surprising to me, because c# is higher-level. EDIT: As people have pointed out, implicit conversion can be just as annoying too. I personally like strong types languages better anyway.

6

u/Beach-Devil i++++; Dec 20 '20

h m that’s sad. Is there still truthiness in c#? Like for example passing ints to if statements?

15

u/[deleted] Dec 20 '20

As far as know, nope. C# is very strong-typed, which I personally like usually, but it can make things like this a bit annoying.

EDIT: spelling

20

u/Willinton06 Dec 20 '20

I mean not to be bitchy but an int just isn’t a book, I know most languages treat it as if it was but it just isn’t, I like that C# doesn’t allow you to use ints as bools, I used to do it all the time back when I was mainly on JS, now I understand better the need for type safety so a good ol bool does the job just fine

1

u/JochCool Jan 17 '21

I mean, it is still possible to make your own types truthy/falsey, which means you can put those directly into if statements. However, most built-in types don't do this for the reasons others mentioned.

28

u/kbruen Dec 20 '20

It's actually not sad at all, and it's this way to prevent errors. Only bools are truthy or falsy. Any other value is not compatible with being true or false.

A great example of why this is a good idea is the Linux API, where almost all functions return -1 in case of error. In C, -1 is treated as a true value.

9

u/XDracam Dec 20 '20

There's a consensus in the academic programming community that implicit conversions between already defined types is a bad practice. It can lead to a lot of issues and hard-to-find bugs. Code might behave entirely differently than expected and it's implicit, so it's hard to figure out.

For example, in C++ (and Scala, where it is explicitly discouraged by a compiler feature flag or custom import), you can define an implicit conversions from string to bool that uses the string as a seed for a random number generator and returns whether the first generated number is even. Does it make sense? No in most cases, but you can do it. And you'll never find the culprit unless you do some clever debugging or happen to stumble upon the externally defined conversion code somewhere.

C# only allows implicit conversions to be defined in the source of one of the types. That way, the conversions are definitely intended and aren't hard to find. This can still lead to issues, like Unity's weird implicit conversions from object to bool. But it's far less likely to be abused.

C# walks the line between "I am expressive enough to not annoy the programmer" (cough Java cough) and "I am idiot-proof enough so that the sleep-deprived intern cannot write code that nobody else will ever be able to understand". Java is on the first end of the spectrum, C++ on the other.

On my last Job, I really liked the fact that we were using Java, because I had some dense coworkers. People on my current job are hand-picked, so C# is fine. But they are not experienced enough for C++.

(C# has some issues with implicit conversions which probably depend on compiler implementation details, like no conversions to interface types; so it's not perfect either)

1

u/Migeil Dec 20 '20

C# walks the line between "I am expressive enough to not annoy the programmer" (cough Java cough)

Could you maybe expand on this? In what way does Java annoy the programmer that C# does not?

4

u/XDracam Dec 20 '20

Java has no extension methods, for one. It also forces package folder structure. Only one class per file. There is no dynamic keyword.

There is no Func because you can't have the same type with a different number of generics. Instead you have to remember interfaces, all with different names and different names for the invoke method or () operator.

There is no operator overloading. No properties (instead you write getFoo() and setFoo(value) for each private field). And there's no => syntax for single expression bodies.

There's also no ref or out parameters. There are also no tuples. Want to return more than one value? Make a custom class with explicit getters and setters.

The main difference for me is the Streams API. In C# you write myList.Select(c => c * 2).ToList(). In java, if memory serves correctly, you write myList.stream().map(c -> c * 2).collect(Collectors.toList) because streams are distinct from eager collections.

There are also other missing features like initializer syntax (new List { 1, 2, 3}) etc.

These aren't all bad things. It makes java more standard and easier to understand for mediocre or bad programmers. It also makes Java easier to learn. I often need to explain some fancy C# code to coworkers with less knowledge of the language. Never had to explain a single Java feature.

Some choices prevent nasty bugs or performance issues. I debugged and helped with many bugs coming from IEnumerables which were sometimes lazy and sometimes eager.

It's always about picking the right tool for the job. Every language has many upsides and downsides. Java is great when you can't guarantee competence, e.g. in a large company where many people may work on the same code. Because you can't do cool and special things.

(Some of these might be outdated by now, I've stopped using after Java8)

5

u/Jmc_da_boss Dec 20 '20

excellent writeup, also worth mentioning async/await syntax

2

u/XDracam Dec 20 '20

Thanks. Definitely!

Async/await is not perfect (see Scala Futures or better Scala cats IO) but it certainly beats whatever Java alternatives there are in terms of convenience.

Now that you mention it, yield return is also very convenient.

2

u/totti173314 Dec 20 '20

pretty sure the => complaint got fixed with the new -> thingy but I am a newbie to this so idk

3

u/XDracam Dec 20 '20

That's for lambdas (anonymous functions), it's not what I meant in this particular case.

In C# you can write int Foo(int x) => x * 2; whereas in Java I'd have to write int foo(int x) { return x * 2; }. It's not much, but it quickly adds up when you have lots of small functions.

1

u/totti173314 Dec 21 '20

I dont know if this is true but if its just one statement you can just throw the braces away as far as I remember. For single statements you dont need a code body.(this might actualy be only for conditional and looping statements idk) The only projects I've done have been small scale 10 or so people projects which take about a month and none of it was like actual workplace stuff because I don't currently have a workplace, so this kind of thing hasn't even occurred to me.

2

u/XDracam Dec 21 '20

This thing is a C# feature where you can replace { return x; } with => x; in almost all places, where x is an arbitrary expression. It's minor but it does add up ^

2

u/SuperSupermario24 while True: print("owo") Dec 21 '20

You can't even explicitly cast an int to a bool in C#. (bool) 1 for example throws an error.

5

u/[deleted] Dec 20 '20

To clarify a couple of comments, this wasn’t copied and pasted, I (sadly) wrote this. I’ve now just changed it to i != 0. Also, thanks to u/H34DSH07 for reminding that extensions exist in c#, I’ll probably be moving my Utils class to extensions to make the code more readable.

2

u/thatwasagoodyear Dec 20 '20

You may also want to see my comment here. Use the built in function instead rather. Less maintenance, more reliable.

199

u/YT_PintoPlayz Dec 20 '20

I scroll through badcode to make me feel better about my own. This isn't bad at all. It's understandable. That can't be said about much of my code. (I'm the masochist who never comments their code)

83

u/[deleted] Dec 20 '20

You only need to comment things are not obvious. Good code itself is documentation.

36

u/blehmann1 depraved Dec 20 '20

I mostly agree. The only exception is APIs and stuff like that. i.e. anywhere the user of your code will not read your code, but instead reads some documentation, likely generated from comments.

9

u/overkill Dec 20 '20

The code I inherited was worse than not commented. The sparse comments that were there where generally copy/pasted along with the original code, which was then changed so the comments no longer bore any resemblance to the code they supported.

Deleting comments makes this code easier to understand

1

u/KernowRoger Dec 20 '20

Drift is a massive problem with comments generally. It's hard enough to get people to do them let alone update them when refactoring.

7

u/cthewombat Dec 20 '20

Problem is, while writing your code you feel that it is obvious because you have been working on that topic for a while. Try giving it to someone new or looking at it yourself in 2 years time. It probably won't be as obvious anymore

2

u/Semarc01 Dec 20 '20

Wellllll You shouldn’t need to describe what the code is doing, true. But you should describe why the code is doing what it’s doing imo. Because I’d someone else (or even yourself after some time) is looking through the code, they might understand a specific part of the code, but getting what that part is doing in the larger context of the whole program is usually not obvious, especially in big Programms.

1

u/TrigamYT Dec 20 '20

Well I'm a dumbass so I need to comment all my code or I'll forget what it does

0

u/Critical-Win-4888 Dec 20 '20

private Boolean scrollBadCodeIntegrityBoost(Optional<Long > imposterSyndromeRatio) { If(imposterSnydromeRatio.isPresent()) { if(imposterSnydromeRatio.get() < IMPOSTER_CONSTANT) { return false } else { return true; } } else { long defaultSyndrome = this.syndrome; return true; }

}

-2

u/cstmth Dec 20 '20

Well, if you flipped it you could do 'return i == 0' (at least in Java)

73

u/--B_L_A_N_K-- if (true == true) {return true;} else {return true;} Dec 20 '20

Image Transcription: Code


        return new Vector3(arr[0], arr[1], arr[2]);
    }

    public static bool IntToBool(int i)
    {
        return i == 0 ? false : true;
    }

    /*Utils.NullableXor(bool? nullable, bool nonNull
     *      ________________________________________
     *     |    bool? a     |       bool b       |
     *     |                |                    |

I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!

0

u/[deleted] Dec 20 '20

[deleted]

17

u/thatwasagoodyear Dec 20 '20

Also, Convert.ToBoolean is already built in with overload support for different input types & formats.

If you're doing tons of conversions and concerned about having Convert. littering your code, add a using static System.Convert; to your using statements to import all of the static methods of the type so that you can call them as if they were a static function local to your type, e.g. ToBoolean(input), ToUInt64(input), FromBase64String(input), etc.

7

u/DaMastaCoda Dec 20 '20

That looks fine since it's more readable

2

u/[deleted] Dec 20 '20

Must have copy pasted the piece of code into the function without giving a second look.

2

u/delubyo10 Dec 20 '20

You can replace that with return i != 0

1

u/CarterNotSteve Dec 20 '20

Create a function with return type bool, that takes one integer argument; is that argument 0? If so, return true.

1

u/CaptainTrip Dec 20 '20

I've really seen much worse here. This is at least correct and easy to read.

1

u/AllenKll Dec 20 '20

Unpopular opinion: this is not bad code.

It's clear. It's concise.

Could it be shortened using !=? Yes, but any decent compiler will optimize that for you. Further there is a coding practice that indicates that using negative operators like "!" Makes code harder to read, where a simple "is equal" check uses less brain power to absorb.

1

u/sebamestre Dec 20 '20

I read about the .NET JIT being better at optimizing this ternary over just the comparison, due to some quirks with its flow analysis phase. (When you have a?b:c it remebers the two possible outcomes, but doesn't do this automatically when it knows a value is a boolean)

Now, this might not be the reason this was written, but it's good to take into account if you're gonna do such a change, specially if it's called in a hot path.

Even if this WAS the reason, it might not be necessary, or even helpful.

Remember, always measure before and after optimizing.

1

u/0vercoded Dec 20 '20

Could be a lot worse. At least it's explicit.

1

u/[deleted] Dec 20 '20

As a javascript dev I don't see what the big deal is! I'd just do `intToBool = (x) => !!x`

I can imagine there is a case where you are receiving an int from an external system that is supposed to represent a bool, and you just need to do a quick translation. nbd? What else would you do?

If you're using ints in place of bools in your code... and it's not coming from an external source... well that's an interesting one.

1

u/[deleted] Dec 20 '20

Clearly you should have made this as an extension method.

1

u/AO_MCHI Dec 20 '20

that’s ok for it, somehow i get confused when handling -1 for true case (like vb and sql )

1

u/__archaeopteryx__ Dec 21 '20

Thats funny. I was just looking at a go GUI library a few min ago on GitHub and I saw the converse of this method -> bool to int... just funny I ran across this gem in the same day. Cheers.

1

u/TheBrainStone Dec 20 '20

Can’t you just cast?

8

u/blehmann1 depraved Dec 20 '20

Not in C#. In a lot of languages you would be able to. C# likes its type safety. You can't even box it to an object and then unbox it back to a different one. Well, the compiler will let you, because at compile time object can be a reference to any type, but at runtime it'll go hold up, this is the wrong type and throw an exception.

Personally, it's a language choice, I would be fine with letting you do it with a cast, as that's still explicit. If someone breaks type safety explicitly then they probably know what they doing. Granted it's less clear what (bool)x means, whereas x != 0 makes more sense to someone who doesn't use languages which let you (or make you) treat integers as booleans. For example, some beginners think that negative integers map to false.

0

u/SerialVersionUID Dec 20 '20

You may wanna throw an error if the value is below 0 or above 1.

36

u/[deleted] Dec 20 '20 edited Dec 20 '20

[removed] — view removed comment

31

u/Nebuli2 Dec 20 '20

I mean, i != 0 is a lot simpler than i == 0 ? false : true.

12

u/fukitol- Dec 20 '20

Is 0 not falsey in C#?

In most languages you just do

if(i) { ... stuff }

17

u/BringAltoidSoursBack Dec 20 '20

It's been a while since I've tried it but I'm pretty sure you cannot implicitly so that in c#. IIRC, you also can't do things like if(null)

5

u/fukitol- Dec 20 '20

Interesting. That's just one of those things I've taken for granted in languages that didn't require pattern matching (like Rust, though I can't say for sure C# doesn't).

4

u/BringAltoidSoursBack Dec 20 '20

It's ok, I use c# for my job and there's a lot of stuff stuff like that in it. Like not being able to have default values for objects in a struct (literally one of my biggest peeves with c#)

3

u/Konomira Dec 20 '20

You can set default values in a constructor for a struct though. Annoying that you can't just set the property like in a class, but the ability is definitely there.

1

u/OrganicBid Dec 20 '20

Tbh a struct is just what came before tuples and is now sorta superceded by records. You should not set default values as it is against the idea behind the struct. If you want complex options, use a class. The overhead is negligible.

3

u/Dealiner Dec 20 '20

Structs have definitely different usages than tuples or records and they work differently too. Also I wouldn't say that overhead is negligible, it really depends on what you are using them for.

1

u/OrganicBid Dec 20 '20

I haven't yet seen a usage of a struct where a tuple couldn't have been used, I haven't seen a usage of struct where a record wouldn't be the same (as far as I can remember), and I would like to see an example of struct usage where a tuple, record, or class wouldn't be better.

I would posit that structs are a remnant of C, of a time when returning multiple values were hard but needed, and that using them for more than transporting immutable values is breaking the design philosophy of OOP in general and structs in particular.

→ More replies (0)

1

u/BringAltoidSoursBack Dec 20 '20

You can, but since you can't have a default constructor, they aren't really default values. There is a way around it using nullables and checking if it's been set but that's gross.

12

u/kbruen Dec 20 '20

Thankfully, in C# only true is truthy and only false is falsey.

1

u/fukitol- Dec 20 '20

These days most of my code is Python or the occasional bit of JavaScript. Compiled apps are written in Go. I've been spoiled.

That said, nobody in my office uses windows. It's either mac or Linux. Not a whole lot of .net happening.

3

u/yonatan8070 Dec 20 '20

Java also doesn't do that and it's so annoying

0

u/fukitol- Dec 20 '20

It's been a while since I've used Java but that's right, thanks for reminding me why I hate Java.

11

u/[deleted] Dec 20 '20

It's only a couple extra characters to type != 0 and it makes it a lot more readable.

1

u/fukitol- Dec 20 '20

Oh I have a lot more reasons for hating Java, that's one of the lesser ones.

1

u/totti173314 Dec 20 '20

Java is way too strongly typed, isn't it?

2

u/fukitol- Dec 20 '20

It's just too verbose and has too much boilerplate for my tastes. And I hate XML with a passion.

1

u/totti173314 Dec 21 '20

Why? I like xml. Learning android is one of the best times I've had learning to code anything. I'm still learning android.

→ More replies (0)

1

u/HereComesCunty Dec 20 '20

Nah, I do it accidentally all the time when I’m switching between js and c#. Compiler always complains

0

u/HTTP_404_NotFound bool isEven(int num) => num%2==0 Jan 07 '21

Or,

Just i > 0

1

u/Nebuli2 Jan 08 '21

i could be negative.

0

u/HTTP_404_NotFound bool isEven(int num) => num%2==0 Jan 08 '21

Sounds like false to me.

1

u/Nebuli2 Jan 08 '21

But... it's not. In languages where you can use numbers as conditions, it is almost always false if and only if it's 0.

13

u/yaxamie Dec 20 '20

Agreed. A ToBool method on Int32 would be dope here

8

u/XDracam Dec 20 '20 edited Dec 20 '20

Depends. Extension method make discovering and learning a codebase much nicer. But I think you shouldn't define domain specific methods as extension methods, because they clutter the suggestions and prompt others to use them even though they might make no sense.

This case is borderline; it uses the established C way of converting ints to bools, no big surprise here. But there are many ways to convert an int to a bool, like .IsEven() or .IsPrime().

This method has no semantics. It doesn't tell the reader anything, it's pure boilerplate. You'd have to read the source to be sure that it's actually a 0 is false conversion and not a 12 is false or any other conversion that might make sense in the current context when you're reading the code. I'd actually recommend replacing every IntToBool(foo) with a foo != 0, because that's shorter, has the same amount of information and is much clearer to understand.

My point about extension methods: they are fine when it is obvious what they do, and when the extension method makes sense for all instances of the type in all contexts. Otherwise, an explicit static method call might add context: CStyleConversions.IntToBool(foo) is obvious for most programmers.

1

u/HereComesCunty Dec 20 '20

.IsNotZero() would be a clearer extension to int32 to get the same result as the proposed .ToBool() right?

Edit: or .IsZero() if you prefer

11

u/Mr2-1782Man Dec 20 '20

I mean if you're using ints to do booleans in a language that did booleans from the start that's a problem IMO.

5

u/Konomira Dec 20 '20

But sometimes unavoidable. Specific example that comes to mind is saving info as a registry key in Unity using PlayerPrefs which only accepts floats, ints, and strings.

1

u/Mr2-1782Man Dec 21 '20

I agree its unavoidable, but in that case I'm blaming the person that wrote the API. Unity was written late enough that it should be a bit more flexible, I can think of a bunch of reasons why you would want more than just float, int, string.

3

u/ign1fy Dec 20 '20

C# can't do the truthiness tricks of JS out of the box.