r/shittyprogramming • • Nov 09 '15

How to parse a boolean

Post image
0 Upvotes

15 comments sorted by

2

u/Pheasn Nov 10 '15

Correct me if I'm wrong, but couldn't a null-pointer input break this?

2

u/Effenheimer Nov 11 '15

You are correct. A null input does break this.

Everybody thinks this code is great, but I shutter at the situation where this code is necessary. Imagine how unreliable the source data must be. I suppose that is a reality of the industry.. Doesn't make it pretty, though.

2

u/scorcher24 Nov 11 '15

I don't know where this is used, by I would make the input a radio selector or something like that in the interface,then all this parsing is not necessary anymore.

24

u/canada_mike Nov 09 '15

you really do have to ensure you cover every possibility. The word 'true' isn't always the only way to describe a condition that is not false. Some people say 'yes'. Computers say 1.

I would improve this method by adding several other languages, after all the german 'nein!' or the russian 'nyet!' will break this. Since text inputs are the best inputs you really have to anticipate what the user will provide you as an answer.

two examples of this, straight out of the simpsons:

  1. Homer, working from home, TRIPLES his productivity by typing 'Y' instead of 'YES'. TRIPLE! Now that is a great result.

  2. When filling out a form, homer writes "ok" in the box marked "do not write in this space". Is he wrong? Probably! But he is the user so we have to anticipate this type of boobery.

In conclusion, booleans are hard. Don't assume it's binary

42

u/mellowmymints Nov 09 '15

There's nothing wrong with this.

I mean, I would return immediately in the case block, but otherwise this is a clean beautiful piece of code.

13

u/homesarstar Nov 09 '15

I know! I feel bad since this looks like what I would do, and I swore I'd reevaluate my education when I saw something on here that I'd write.

2

u/natziel Nov 09 '15

His first mistake is not using any ternary operators

10

u/[deleted] Nov 09 '15 edited Nov 09 '15

Whats funny is that this is how PHP's boolean comparison operator probably works underneath.

5

u/gigimoi Nov 09 '15

There's nothing that wrong here. It's not localized, but that might not be a relevant issue, and it can easily be changed to localized.

1

u/[deleted] Nov 19 '15

i'm assuming this is used as such

for each xml value input
  try 
    result = ParseBoolean(input) != NULL || 
      ParseString(input) != NULL ||
      ParseNumber(input) != NULL // more data types ...
 
  catch
    // invalid xml

-2

u/fazzah Nov 09 '15 edited Nov 09 '15

Somebody tell him about capital letters.

EDIT: yes, my bad, didn't notice toLower()

9

u/BackwardsBinary Nov 09 '15
input.ToLower()

Line 4 of OP's code. I'm gonna go ahead and guess this parses the input into lowercase.

1

u/ncsurfus Nov 09 '15

The input string is converted to lower case.

1

u/[deleted] Nov 09 '15
switch (input.ToLower()) {...}