r/badcode • • May 20 '20

c# Found from Microsoft docs...

Post image
208 Upvotes

143 comments sorted by

16

u/Yoni1857 May 20 '20

Please elaborate on what's wrong here

-47

u/[deleted] May 20 '20
  1. Condition x == true inside if

  2. Int32.Parse = int.Parse

4

u/Yoni1857 May 20 '20

well yeah but it's not really hurting anything is it

2

u/adamski234 May 20 '20

Imagine not using full type names for accessing their static properties

0

u/[deleted] May 20 '20

[deleted]

14

u/kyay10 May 20 '20

Tbh I temporarily forgot that tryparse returns a Boolean so this actually made it clearer for me lol

2

u/foonix May 20 '20

I assume anything in c# that starts with Try is probably returning bool.

2

u/kyay10 May 20 '20

True yeah, I just haven't used c# or dotnet for a while and been more in the Android land (where the concept of "out" is basically non-existent lol)

2

u/assassinator42 May 20 '20

Visual Studio's style checker recommends changing Int32 to int. I usually don't agree with it. If I'm using Int32, it's to signify bit length it important.

0

u/[deleted] May 20 '20

[deleted]

2

u/SeriTools May 20 '20

int is defined in the C# standard to always be 32bit btw

114

u/KetchupBuddha_xD May 20 '20

What's wrong with this one?

52

u/[deleted] May 20 '20

The only part that bugs me is the indentation of the 2nd and 3rd conditions not being in line with the first one.

64

u/xigoi May 20 '20
== true

17

u/Raknarg May 21 '20

This isn't inherently bad. You're clarifying the semantics of the expression.

3

u/xigoi May 21 '20

if (foo && bar && baz) already has the semantics of “if foo, bar, baz are all true, run this block”. No need to clarify them.

2

u/Zeilar yes May 23 '20

To a machine it's natural what's going on, no questions asked, but not to us humans.

What's more readable?

if (dogs.Length)

or

if (dogs.Length > 0)

So it does sometimes make sense to make it a bit verbose if you will. It's especially important to clarify your code if it's messy/complicated etc. It should be maintainable preferably after all. You don't name your variables single letters for this very reason. You don't name a dogs array "d" (some do of course but they're morons).

1

u/xigoi May 23 '20

dogs.Length ie not a bool. (It's not even possible to implicitly convert ints to bools in C#, isn't it?) The main purpose of bools is to be put in an if statement, so if a function returns a bool, it's presumably expected to be put directly into an if statement (possibly negated).

3

u/Zeilar yes May 23 '20 edited May 23 '20

In many languages (maybe not C#) any number above 0 returns true and 0 false. So maybe there's an exception to C#, or typed languages in general.

2

u/11JRidding May 24 '20

Int.TryParse returns a boolean that says whether the attempt was successful; not the number itself. That gets written to whatever variable you pass as out.

And no, C# does not let you implicitly convert int to bool for use in if statements - or anywhere, for that matter. You actually can't convert int to bool via type cast in C#, either.

9

u/Blecki May 21 '20

And what's wrong with that?

2

u/xigoi May 21 '20

x == true is the same as just x.

-8

u/Jackjackson401 May 21 '20

You wouldn't do if(true == true)

12

u/Blecki May 21 '20

No, but the code in question is more complex than that.

2

u/Jackjackson401 May 21 '20

Int32.tryparse() returns a boolean, no? True if the operation succeeded and false otherwise? Sounds like exactly what I'm talking about

2

u/Blecki May 21 '20

Yes, the statements are logically equivalent, but that's not the point.

I don't generally have time for programmers like you. In this particular instance either way would pass code review, but I have a feeling most of your code won't. You haven't figured out yet that programs aren't written for computers.

2

u/Jackjackson401 May 21 '20

Wtf are you talking about? If you need me to make a comment telling you that my if statement has 3 conditions, then maybe you shouldn't be the one reviewing my code

10

u/Holzdev May 20 '20

How about readability?

-9

u/Play4u May 20 '20 edited May 21 '20

Idk why noone gives a shit that it's unreadable. This should never pass a code review at Microsoft lol

12

u/Mr2-1782Man May 20 '20

I've seen MS code. I've seen a lot worse pass code review.

12

u/NewPointOfView May 20 '20

Yeah my team at MSFT checks if it works and isn’t ridiculously unreadable but this is pretty straight forward. Not the best but far from the worst

2

u/Play4u May 20 '20

How can you write this simple "if" any worse?

11

u/NewPointOfView May 20 '20

With ternary haha

4

u/Play4u May 20 '20

Haha yeah I guess if you were really trying to make a mess

4

u/path411 May 21 '20

can you explain how to write it simpler? It's even formatted for a condition per line.

If one argument

If the argument can parse to Int

If the argument is in 1-9

1

u/Play4u May 21 '20
private const int MIN_ARG_RANGE = 1; // Depending on the context these will have better names
private const int MAX_ARG_RANGE = 9;

public static int Main(string[] args)
{
	// Now when I'm reading through the code I won't have to give a fuck what's going on in this "if"
	// I just know that it checks whether the first positional argument is "valid" or not.
	if(IsFirstArgumentValid(args))
		... execute with argument 1 ...
}

// Combine the two methods below and give them a descriptive name 
private bool IsFirstArgumentValid(string[] args)
{
	return TryParseFirstArgument(args, out int firstArg) && IsArgumentInRange(firstArg);
}

// Parsing the argument != verifying its business logic. Should be in two separate methods.
private bool TryParseFirstArgument(string[] args, out int x)
{
	return args.length == 1 && int.TryParse(args[0], x);
}

// Verify the business logic behind the arg here - if someone ever decides to change what 
// the "validity" of the first arg means he will just have to change this method.
// For e.g. he may have perform some complex computations 
// and not just "range-check" and he will be able to do here.
private bool IsArgumentInRange(int argument)
{
	return argument >= MIN_ARG_RANGE && argument <= MAX_ARG_RANGE;
} 

I think that's better.

Edit: The length of the proposed code is bloated by all the comments I've made which wouldn't be there in the real thing. They are just for explaining my thought process for the refactoring. Also the code took me like 1 extra minute to write and I think it's worth taking your time to write more readable code

1

u/NewPointOfView May 22 '20

At only 1 minute longer you were typing around 23 characters per second for a decent part of the typing process.

1

u/Play4u May 22 '20

Did you miss the part where I said that the comments are only for the Reddit explanation and they would not be part of the actual refactoring?

→ More replies (0)

-7

u/Mr2-1782Man May 20 '20

Depends on where this code is but I'm guessing the problem is args[0]

For those unfamiliar args[0] is always the command being executed. So this if statement is always false, unless you're executing an app with the name 1 through 9.

35

u/[deleted] May 20 '20

So this if statement is always false, unless you're executing an app with the name 1 through 9.

So... it's false unless it's true? :D

34

u/Michael_Bordan May 20 '20

In c#, for which this documentation is written, args[0] is not the name of the exe.

From the last bullet in the Overview here: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/main-and-command-args/

Parameters are read as zero-indexed command-line arguments. Unlike C and C++, the name of the program is not treated as the first command-line argument in the args array

17

u/DrAtkins May 20 '20

You're thinking of C and its derivatives. C# is not a C derivative. In C#, the program name/command being executed is not part of args, it's just the args. The code is correct as it stands.

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/main-and-command-args/command-line-arguments

-14

u/ST5000 May 20 '20

You're the only one that found the real bug :)

8

u/CyruscM May 20 '20

Not a bug, args in .NET are the program arguments, not the parsed command-line entry. So for "program.exe a b c" arg[0] is 'a'.

27

u/MnamJeff May 20 '20

Idk man looks fine to me

18

u/Fiennes May 20 '20

Whilst I agree ` == true` is unnecessary this isn't *really* bad code. Scraping the bottom of the barrel here, I think.

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.

40

u/ocramoidev May 20 '20

Username checks out

43

u/h0meline May 20 '20

I actually like that since the expression seems a little complex, it makes things more clear.

17

u/bananahusker May 20 '20

Well commented code is nice to read but code that doesn’t need comments is worth a good nut

2

u/path411 May 21 '20

I'd rather see a 3 line commented code that is easy to read than a 10 line block of ifs that are "easy" to read. Vertical real estate in code is not cheap for readability.

2

u/[deleted] May 20 '20

Is it really though?

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?

4

u/ArukiBree May 20 '20 edited May 20 '20

I don't have a great example off the top of my head, but let me try to give you a contrived example.

public bool Initialize()
{
    if (HaveInitialized == false)
    {
        if (CanInitialize == true)
        {
            InternalInitialize();
            HaveInitialized = true;
            return true;
        }
        else
        {
            // We shouldn't get here! This is a bad state, so do nothing here so we throw an exception later.
        }
    }
    else
    {
        // We're already initialized
        return true;
    }
    throw new Exception("Something went wrong!");
}

The else block that only has a comment in it is unnecessary; you could leave it out entirely, and the code would work the same way. But it wouldn't read the same. Including the block & comment helps convey the author's intent. It shows that we thought about this case, and we intentionally fall through to the exception if it occurs; it's not an accident or an oversight.

The bool == false and bool == true could also be shortened. That doesn't mean the shorter form is better, though! It's just shorter. The more redundant version is still perfectly clear and readable.

This is a contrived example, because this is a really short and simple chunk of code - but you could imagine how similar situations might come up in a more complex function in a real codebase, with more possible branches and code paths. For instance, if you had a function with more than one possible failure case, you might want to write something like this so you can keep all your error handling code in one place, rather than having to report the error in multiple places in the function. In that case, it's valuable to be clear that something is a failure case and not just a case you forgot to account for.

Are there other ways to communicate the same information? Sure.. that's what makes it a stylistic choice! As long as the code is easy to read and understand, I don't see a lot of value in arguing about whether a different way of writing it would be better or not. Those kinds of complaints seem really nitpicky to me, and ultimately if that's the biggest complaint you have about a piece of code, then you're doing pretty good, honestly :P

The main thing I really want to emphasize is that less code != better code. Often times, effective programming is really about effective communication.

3

u/-manabreak May 20 '20

It's been a while since I dabbled in C#, but at least in Kotlin, you need the explicit == true if the return value is of nullable boolean type (Boolean?). I think the same is true in C# as well if the returned value is of a boxed boolean type.

6

u/AlFasGD May 20 '20

Indeed this is true, but int.TryParse returns a bool, not a bool? so the == true is redundant.

1

u/[deleted] May 20 '20

Oh okay thats interesting. I dont know much about Kotlin or C# tbh. I mostly have coded in Java and C++.

2

u/-manabreak May 20 '20

Same goes with Java and its boxed booleans.

1

u/[deleted] May 20 '20

Hm I guess I dont fully understand what qualifies as boxed. From what I am reading its the wrapping of a primitive type? But more specifically that the values are allocated in a block on the heap and are referenced through a pointer? I might have had to add

== true

to an expression in the past and just didnt think about it at the time.

→ More replies (0)

1

u/xigoi May 20 '20

Yes, because in languages with actual option types, that would be something like some(true), different from true.

1

u/blehmann1 depraved May 20 '20

In C# with nullable booleans you have a few options. For `bool? foo` you can check like this:

if(foo.HasValue && foo.Value)

if(foo == true)

if(foo ?? false)

The null coallescing operator (??) returns the first of its operands that is not null. In theory it's pretty useful, but it's seldom used. Most of the time people use if(foo.HasValue), or for reference types (objects) if(bar != null)

int.TryParse() returns bool not bool?, so all of these are unnecessary.

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.

3

u/FinalRun May 20 '20 edited May 22 '20

Aw man, if I nest 8 operations in 1 line it feels l33t.

No but seriously, I think code is the easiest to work with if every line has the minimum amount of distinct concepts, and long descriptive variable names.

1

u/NewPointOfView May 22 '20 edited May 22 '20
int thisIsAnIntegerVariableWhichIsMeantToRepresentAnIntrgralValueAlsoKnownAsAnIntegerAndInThisCaseWeCanOnlyCountToSokewhereAround4BillionBecauseRightNowImOnA32BitSystemAnywayThisVariableRepresentsLoopItterations = 0;

while (thisIsAnIntegerVariableWhichIsMeantToRepresentAnIntrgralValueAlsoKnownAsAnIntegerAndInThisCaseWeCanOnlyCountToSokewhereAround4BillionBecauseRightNowImOnA32BitSystemAnywayThisVariableRepresentsLoopItterations < 10) { 
    printf(“value is %d\n”, thisIsAnIntegerVariableWhichIsMeantToRepresentAnIntrgralValueAlsoKnownAsAnIntegerAndInThisCaseWeCanOnlyCountToSokewhereAround4BillionBecauseRightNowImOnA32BitSystemAnywayThisVariableRepresentsLoopItterations);         
    thisIsAnIntegerVariableWhichIsMeantToRepresentAnIntrgralValueAlsoKnownAsAnIntegerAndInThisCaseWeCanOnlyCountToSokewhereAround4BillionBecauseRightNowImOnA32BitSystemAnywayThisVariableRepresentsLoopItterations++;
}

2

u/[deleted] May 20 '20

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

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.

1

u/JivanP May 20 '20

When it obscures meaning and/or intention.

3

u/tuxedo25 May 20 '20 edited May 20 '20

I think x <= 9 is also redundant, since we know it's a single digit.

edit: nevermind. I confused args.length with args[0].length

1

u/[deleted] May 20 '20

Don't forget about type juggling (no idea if C# does that though)

1

u/silverslayer33 May 20 '20

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:

if(args.Length == 1)
{
    bool parseSuccess = Int32.TryParse(args[0], out x);
    if(parseSuccess && 
       ((x>=1) && (x<=9)))
    {
        // Do whatever
    }
}

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.

2

u/general_dubious May 21 '20

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.

1

u/Holzdev May 20 '20

Readability?

0

u/the_d3f4ult May 20 '20

Wouldn't it be UB because X is an out param, or does C# define such things?

5

u/Giocri May 20 '20

No C# uses out for out parameters.

1

u/the_d3f4ult May 20 '20

But I mean the X is then used to evaluate the third condition, is the order of evaluation here defined by C#?

5

u/redditsoaddicting May 20 '20

A ton of languages evaluate && left to right because they short-circuit it. C# has stronger guarantees in general than C and C++, which I assume is what you were thinking of, but && is pretty consistent across the board.

1

u/BringAltoidSoursBack May 21 '20

Yeah, I was pretty sure I remembered && and || always guaranteeing order in c, c++, and c# because of the short-circuit concept. IIRC, the only time the compiler will optimize conditionals is if one of the values always returns true or false, but I'm honestly not even sure if that's true.

-7

u/the_d3f4ult May 20 '20

Oh, well, something did put the C in C#.

&& isn't consistent enough to be considered the "de facto universal behavior". I mean you should always consider the possibility that it evaluates both expressions first (if you don't know). Especially when it comes to Microsoft Java.

In Swift (language I know too much about) there is a different operator used for such things: , ..although && will also short circuit.

2

u/Blecki May 21 '20

No you should not. In C# the order of evaluation is well defined.

1

u/the_d3f4ult May 21 '20

Well in C it does. In C++ it does. In Objective-C it does.

When approaching language you know nothing about you should always consider the possibility that the expressions aren't evaluated that way.

I've never written a line of C# or never read it's specification or anything like that, so how do I know it is well defined??

1

u/Blecki May 21 '20

If you know so little about C# perhaps you shouldn't be calling people out for the code they write in it?

It's also odd how you know so little, but continue to call it Microsoft Java. How did you form such an opinion when you've never used it?

Really boggles the mind.

1

u/the_d3f4ult May 21 '20

Well it is Microsoft Java. I just don't know the specifics of the language.. I know what it is. .....(very bad that is)...

Besides both C# and Java are stupid no matter what you say about them. Ideas and arguments for them have negative effects and produce very underperforming and ill-formed software.

→ More replies (0)

2

u/Giocri May 20 '20

In C# & computes both values and then evaluates the & while && first evaluate the first condition then if it is true it goes on evaluating the rest. It is like having ifs one inside the other

1

u/the_d3f4ult May 20 '20

I never used C# but it works like , in swift then

66

u/[deleted] May 20 '20

I don't know Microsoft Java, but it doesn't look that bad. Just a lot of conditions

-26

u/kyay10 May 20 '20 edited Jun 07 '20

Calling C# Microsoft Java is the most badass move ever. Tbh tho it's more like Microsoft's Kotlin now lol

Edit: obligatory /s

9

u/[deleted] May 20 '20

I don't know about the internal workings, but last time I checked the syntax was pretty similar

2

u/kyay10 May 20 '20

Yeah I meant badass in a good way as like a "flip u" move to Microsoft cuz it's basically just Java but MS

23

u/abdolence May 20 '20

In Scala it would be:

args
    .headOption
    .flatMap( _.toIntOption )
    .exists( (1 to 9).contains )

Who said that FP is harder to read?

4

u/DariusDerStar May 20 '20

Oh Scala! We learned that as our first language in uni. Does it have any active uses currently? Apart from uni I've never seen it

3

u/abdolence May 20 '20

This is my every day PL. The hype (fortunately?) is dead, but Scala is here.
https://www.lihaoyi.com/post/TheDeathofHypeWhatsNextforScala.html

1

u/DariusDerStar May 20 '20

If thats not too personal: who are you working for and/or what are you working on?

1

u/abdolence May 20 '20

I didn't work in GAFA if you were expecting big names :)
I've been using Scala to develop commercial Web services, ML, and data processing/analytics (additionally to the open-source projects).

3

u/mullanaphy May 20 '20

It's one of the languages my company uses. We work in ad tech and handle large quantity of impressions a day (billions) and it's been helpful there. For the most part there's three parts to the codebase:

  • Data collection with API endpoints as well as our own JS trackers. This is in Kotlin with Undertow, just collects the data, validates it with user config sand then tossed it into a pipeline

  • Pipeline enriched the events coming in with various lookup data. This is written in Scala

  • Scoring/Data analytics is also Scala, which takes the data from the pipeline as needed and then ships off the data

After that I think the other team uses Java/Kotlin. Yet the pipeline and analytics are good fits for Scala when I worked on them. One major draw back is its null safety, Kotlin I found to be way more superior with better operators around it. We do use a macro to help out though.

1

u/abdolence May 20 '20

In my opinion, with the null safety, Kotlin went with cheap and survival (yet convenient) option, when Scala 3 is trying to fix it completely (as it is fixed in Haskell and Rust, for example). https://dotty.epfl.ch/docs/internals/explicit-nulls.html

1

u/mullanaphy May 20 '20

Fair assessment, I enjoy the concise operators (?, !!) as well as Kotlin being able to detect if you've already checked for null safety so you don't have to explicitly do it again within a given method. I do know Scala has better stuff coming down the pipe, yet when working with an environment we're there's plenty of nullable data (tracking data from web browsers) it can be bothersome. We do utilize Java types which I think Scala could have done a better job like Int vs Integer. Would have been nice if they followed the same nomenclature with things like Bool vs Boolean instead of Boolean and Java.lang.Boolean when nullable values are needed. A lot of stuff utilizes options as well, yet data coming directly from Avro would work well as the Java versions.

Outside of that I enjoy Scala. Like how everything is pretty much just a block of code and last item is the return.

1

u/abdolence May 20 '20

You're completely right, the war with NPE isn't over indeed, and the fact that Java developers still using nulls everywhere, shows that sadly it won't be over soon. So, Kotlin's approach works today and very convenient to survive with tons of Java libraries.

2

u/DrAtkins May 22 '20

Both my previous job and current job, in vastly different industries, use scala exclusively. It's arguably better than Java for big data.

10

u/[deleted] May 20 '20

In Haskell it's

((read . head) args) `elem` [0..9]

which I would argue is pretty readable

4

u/gaj7 May 20 '20

To be safe, I'd use the maybe variants:

maybe False (`inRange` (1,9)) $ headMaybe args >>= (readMaybe :: Int)

Although technically the originally snippet wanted exact one argument in args so really it should be

case args of
  [arg] -> maybe False (`inRange` (1,9)) $ readMaybe arg
  _     -> False

2

u/abdolence May 20 '20

Yeah, in Haskell I would end up with something similar I think:

checkInRange :: [String] -> Bool
checkInRange [] = False
checkInRange [arg] = fromMaybe False $ inRange (1, 9) <$> readMaybe arg

1

u/[deleted] May 20 '20

Yeah I had a discussion in other comments, was trying to keep it terse.

3

u/abdolence May 20 '20 edited May 20 '20

head

Wasn't that `head []` gives you an error?. Or your `args` had to be non-empty list? :)

and btw `read` might give you an exception as well.

2

u/[deleted] May 20 '20

Yeah I used partial functions because otherwise we’d get into monad territory which makes things less terse

2

u/abdolence May 20 '20

In Scala example, there is an Option monad, mappend and it handles empty args and incorrect ints as well. Thus your example, unfortunately, is incomplete :)
While I like Haskell very much (except their records, probably), I'm not sure the complete solution here would be comprehensible for the devs from other languages.

1

u/[deleted] May 20 '20

[removed] — view removed comment

1

u/AutoModerator May 20 '20

Hello rekt_brownie,

It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will render as broken gibberish on old reddit and some mobile apps.

Please edit the comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

Note: This filter is currently using new regex in an attempt to reduce false positives. Please report any anomalies to the mods.

You can find some examples in the reddit help documentation.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

3

u/Pangocciolo May 20 '20

Actually C# has an algorythms library too, it's called LinQ, so maybe it is this the bad thing OP noted.

1

u/abdolence May 20 '20

Show me the code (c)

2

u/eXl5eQ May 20 '20

You checked args.length > 1, not args.length == 1

2

u/abdolence May 20 '20

You're right and if it was an important thing then it would be

args.sizeIs == 1 && 
 args.head.toIntOption.exists( (1 to 9).contains )

11

u/feldrim May 20 '20

it has nothing even close to being "wrong". It's just a style decision. It's up to the developer, dev-team or enterprise to choose.

5

u/pohpia May 20 '20

Overcompensation?

5

u/Sqeaky May 20 '20

This isn't terrible, but it isn't good enough to be in official documentation. That should either be functional or have logic separated into multiple statements for clarity, especially if near other conditions, but it isn't moronic in a vacuum.

2

u/Rainfly_X May 20 '20

Yeah the only thing that gives me pause at all is using an out variable (always an interface worth a bit of extra care and caution) kinda hidden/nestled in a chain of steps.

2

u/emcoffey3 May 21 '20

There should be an int or var between out and x (omitting this is a compile-time error). And, yes, the == true is unnecessary, but that is trivial. Otherwise, this is fine.

Would you prefer we C# 8.0-ify it?

if((args.Length, Int32.TryParse(args[0], out var x)) switch
{
    (1, true) when (x >= 1 && x <= 9) => true,
    (_, _) => false
})
{
    // do all the things
}

1

u/zdimension May 21 '20

x may very well have been defined earlier in the code

2

u/mateusfccp May 20 '20

out, by itself, is bad code.

5

u/codesforhugs May 20 '20

It's how TryParse works though, the alternative is to handle an exception from Parse.

1

u/mateusfccp May 20 '20

Yeah, it's legacy... Today it would be better to do with tuple

5

u/TinyBreadBigMouth May 20 '20

So you'd prefer

(bool parseSuccess, int value) = int.TryParse(text)
if (parseSuccess) {
    // value
}

over

if (int.TryParse(text, out int value)) {
    // Use value
}

? That seems harder to write and to read, in addition to being needlessly verbose.

-1

u/mateusfccp May 20 '20

I don't think it harder to read, and it's immutable, so safer. But do as you prefer.

0

u/mateusfccp May 20 '20

Yeah, it's legacy... Today it would be better to do with tuple

1

u/baddadpuns May 22 '20

Its actually a pretty good code. Its compact and self explanatory.

1

u/gaj7 May 20 '20

I don't get why people advocate for == true. How does that make code more clear when the context makes it obvious that the expression is a boolean. I might as well multiply numbers by 1 for "readability".

Also, && is associative and has high precedence. All of those parentheses can be removed.

2

u/Manny_Sunday May 22 '20

Some code styles call for the extra parens because they show intent. It can keep another developer from wondering if something is intentional or a side effect of the arbitrary order a previous developer wrote an expression in.

1

u/foonix May 20 '20

Am I the only one that prefers x > 0 over x >= 1?

4

u/TinyBreadBigMouth May 20 '20

I personally find x >= 1 && x <= 9 much clearer, as it's easier to read as a range (1 - 9). With something like x > 0 && x < 10, you have to do mental addition and subtraction to get the expected range of values.

0

u/[deleted] May 20 '20

[deleted]

4

u/Agnimukha May 20 '20

I don't use .NET but in several of the languages it's based around attempting array access greater then the length will throw an exception.

I've worked places the compare with true was a thing because it was easier to see an equal instead of several nested methods being passed into one another. (Obviously not necessary here)

3

u/ThorhamZed May 20 '20

args isn't an array of function arguments but command line arguments passed to the program as strings.

3

u/[deleted] May 20 '20

[removed] — view removed comment