5
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
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
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!
9
0
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
2
2
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
1
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
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
objectand then unbox it back to a different one. Well, the compiler will let you, because at compile timeobjectcan 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)xmeans, whereasx != 0makes 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
36
Dec 20 '20 edited Dec 20 '20
[removed] — view removed comment
31
u/Nebuli2 Dec 20 '20
I mean,
i != 0is a lot simpler thani == 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
Dec 20 '20
It's only a couple extra characters to type
!= 0and 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
icould 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
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 falseconversion and not a12 is falseor any other conversion that might make sense in the current context when you're reading the code. I'd actually recommend replacing everyIntToBool(foo)with afoo != 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
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?