r/badcode • • Jun 23 '20

java 'val' is a boolean value.

Post image
1.0k Upvotes

58 comments sorted by

69

u/Bluebearsuper Jun 23 '20

CONTEXT: This function is inside a class which wraps a boolean. There is another function (really should have included that now that I think about it) that returns val. They will return the exact same thing, and the '== true' part is pointless.

13

u/Siggi_pop Jun 23 '20

Sure it's pointless, but it doesn't affect performance and at best, it highlights to the reader that val is indeed a bool, so you don't have to look elsewhere for that information. So basically, it's not so bad.

8

u/garfield1147 Jun 23 '20 edited Jun 23 '20

it highlights to the reader that val is indeed a bool, so you don't have to look elsewhere for that information

You cannot really infer that val is a bool[ean], and that there is not autoboxing for a Boolean.

Seeing this, I would rather start worrying of getting an NPE, and have to check if the author by mistake used Boolean for "val".

18

u/oxetyl Jun 23 '20

You already know val is a boolean because isTrue is declared as boolean

129

u/INeedAFreeUsername Jun 23 '20
if (val == true) {
  return true;
} else {
  return false;
}

106

u/[deleted] Jun 23 '20

if (val == true) { return true; }
else if (val != true) { return false; }
else { throw "this should never happen"; }
return false;

67

u/[deleted] Jun 23 '20

//TODO: this happened once, maybe fix it?

26

u/NightHunter311 Jun 23 '20

There's a chance val might be null...

16

u/[deleted] Jun 23 '20 edited Jun 23 '20

That depends on the language. If it's a C-style language or, as in this case, Java, then no

3

u/someone4else Jun 24 '20

Well, if you use Boolean, then you can get this

4

u/[deleted] Jun 24 '20

Pretty sure it doesn't work because a Boolean doesn't equal to true or false, you'd have to call the Boolean.booleanValue() method

9

u/Kernel_Internal Jun 24 '20

autoboxing yo

3

u/[deleted] Jun 24 '20

Ahh I stand corrected

3

u/techyolofam Jun 24 '20

Best solution imo is to use BooleanUtils.isTrue() Takes care of all cases.

14

u/villi_ Jun 24 '20 edited Jun 24 '20

That's way too ambiguous, how will anyone understand what that function does? You need to use Propertm programming style

/* First, check if the value is true. There are only two possibilities for this value in this language, true or false. This value is stored in the 'val' field, and since it is a Boolean we can compare it to true and false using the equality operator, like so: */
if (val == true) {
    /* Then we know this value is true, so return true. This will exit the function.
    return true;
} else if (val == false) {
    /* If the value fails the previous check, then we know that it is not true. If it passed this check, then we now know that it is false, so we then return false.
   return false;
}

// TODO: unit test so we know for sure that this function returns true if the value is true and false if the value is false.

6

u/blehmann1 depraved Jun 24 '20

Nononono you can't just pass in the parameter, think of how improper (TM) that is. You need to pass it in through dependency injection, create an IManagerServiceFactory to take care of it for you instead

1

u/villi_ Jun 24 '20

Ah yes, thank you for the correction. I almost went against my religion - encapsulation.

3

u/AutoModerator Jun 24 '20

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 not render correctly on old reddit and most mobile apps.

For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

villi_, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

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.

10

u/AutoModerator Jun 23 '20

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 not render correctly on old reddit and most mobile apps.

For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

INeedAFreeUsername, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

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.

9

u/DoYouEverJustInvert Jun 23 '20
if (val == true) {
    return val == true;
} else {
    return val != false;
}

-1

u/AutoModerator Jun 23 '20

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 not render correctly on old reddit and most mobile apps.

For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

DoYouEverJustInvert, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

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.

2

u/[deleted] Jun 24 '20

public boolean isTrue(boolean val)

{

return isTrue(val)

}

2

u/[deleted] Jun 24 '20

I used to do this in C# before I learned you can just stick val in :(

1

u/INeedAFreeUsername Jun 24 '20

Yeah same it blew my mind when I understood that boolean logic could be returned

1

u/Ezequiel-052 Jun 24 '20

Error: StatementTooRedundant

1

u/brkpxy Jul 03 '20

if (val == true) { return val; } else { return val; }

103

u/Auerros Jun 23 '20

Peak OOP

56

u/Conman660 Jun 23 '20

You mean OOF

13

u/MCWizardYT Jun 23 '20
public boolean isTrue() {
  return val;
}

this depends on the code using isTrue though.

14

u/Harry10932 Jun 23 '20

Peak refactoring

2

u/Isvara Jun 24 '20

Maybe, but it depends on the language and the type of val. The posted code differs from yours in a language where == performs a non-strict comparison, but returning something that doesn't match the return type doesn't cause a coercion. I don't know whether such a language exists.

1

u/blehmann1 depraved Jun 24 '20

C#, but only if it's a nullable boolean (bool?)

return val == true is equivalent to val.HasValue() ? val : false, which is a shorthand for:

if(val.HasValue()) { return val; } else { return false; }

You can also do return val ?? false because of the null coalescing operator, but it isn't common. Basically the ?? operator returns the first (leftmost) non-null operand. And it evaluates lazily. So you can in theory chain them like this:

`return foo ?? bar ?? baz ?? throw new ArgumentNullException();

Even though this syntax is convenient it isn't used very much.

2

u/Isvara Jun 24 '20

What's the type of throw in C#? Is there a bottom type?

0

u/blehmann1 depraved Jun 24 '20

wdym?

The method does not return an exception, the expression is just lazily evaluated. e.g. if foo is not null it just returns foo and does not evaluate the rest of the expression. If it reaches the throw the method does not return anything, it just throws.

If you mean what is the base type of ArgumentNullException, all exceptions are derived fromSystem.Exception

2

u/Isvara Jun 24 '20

The expression foo ?? bar ?? baz ?? throw new ArgumentNullException() must surely have a type substitutable for boolean, since that's the expected return type. I assume a ?? expression has the type that's common to both operands.

I don't know a lot about C#, but for example in Scala, which is a similar language in many ways, a throw expression has the type Nothing, which is a subtype of Boolean (and also of every other type), which is why an expression like that would compile.

0

u/blehmann1 depraved Jun 24 '20

Throw is of type System.Exception but that is not returned. throw returns nothing, this is just syntactic sugar.

This would compile to the same MSIL (an assembly-like intermediate language that C# uses) as this:

` if(foo.HasValue()) return foo;

else if (bar.HasValue()) return bar;

.

.

.

else throw new ArgumentNullException()

`

Say the calling code looked something like this:

` bool x;

try {

x = ReturnBoolOrThrow();

} catch(ArgumentNullException e) {

Console.WriteLine(x); //This will not work, x is uninitialized

} `

And if there were no catch statement then the program would just exit.

2

u/Isvara Jun 24 '20

I looked it up in the C# reference out of curiosity.

The type rules are as follows:

  • A throw_expression has no type.

  • A throw_expression is convertible to every type by an implicit conversion.

That explains how it works without a bottom type, but it doesn't seem very elegant.

9

u/greenismyhomeboy Jun 23 '20

I mean, it does exactly what it's supposed to do, I guess.

4

u/Mancobbler Jun 24 '20

Terrible code. What you should done is:

npm install isTrue

13

u/Nick433333 Jun 23 '20

Nothing wrong as long as you remember that it’s boolean, it would be a lot easier to judge how bad this is if the rest of the code was there

4

u/MathSciElec Jun 23 '20

Nothing wrong? There’s an unnecessary comparison, and I doubt the function itself is even necessary...

3

u/Mr2-1782Man Jun 23 '20

I think we can make this better:

public boolean isTrueP() {
  if (val == true) {
    val = true;
  else if (val == false) {
    val = false;
  }
  return val;
}

5

u/[deleted] Jun 23 '20

Why tho’?

2

u/Monkey_Adventures Jun 23 '20

I used to like java, but lately it's starting to suck

2

u/MrMercure Jun 23 '20

No, val is undefined mate.

1

u/wind-raven Jun 24 '20 edited Jun 24 '20

Eh. As someone who works in multiple languages and 2 with similar looking syntax (JavaScript and C#) bu very different type systems, this is something I may have written when working with both and dealing with truthy and falsey values in one language and just doing the same thing in the language without truthy and falsey types.

typescript also has truthy and falsey values. Depending on the languages the dev who wrote this mainly works in I wouldn’t even blink at this.

1

u/saadawp Jun 24 '20

Meanwhile in JavaScript land - val?"":""

-2

u/F54280 Jun 23 '20 edited Jun 23 '20

This is not bad code. It is "slightly inelegant" but more readable code (because it is a only return from a function). If would be "inelegant" when used in a if, say in: if (val==true). It starts to be bad when reaching levels of if (val==true) return true; else return false;

But a simple comparison with true? Absolutely not worth of a post here. Here are 663000 occurrences using a simple google search

Edit: lol @downvoters that have no idea what actual badcode looks like

2

u/Mr2-1782Man Jun 23 '20

I think you don't understand what the problem with this code is. It isn't the comparison, rather its the fact that someone built an entire function around a builtin operator that uses said operator.

3

u/lachlanhunt Jun 24 '20

It's also the fact that the one variable they are relying on, val, is undefined (or defined in a different scope that's not shown).

1

u/F54280 Jun 24 '20

Sorry? This is not javascript, this is java. It means var is defined somewhere.

Or is the definition for being accepted by r/badcode so low that compiling isn't even a requirement anymore?

2

u/F54280 Jun 24 '20 edited Jun 24 '20

I think you don't understand what the problem with this code is.

Uh? It is obvious, at first glance, that this is an instance method.

When I saw the code, the way I understood it is that it is potentially part of something like:

interface Testable
{
    public boolean isTrue(); 
}

with somewhere else:

class BooleanConstant implements Testable
{
    boolean val;
    BooleanConstant( boolean aValue ) { val =  aValue; }
    public boolean isTrue() { return val==true; }
}

class AndExpression implements Testable
{
    List<Testable> arguments;
....
}

class BooleanVairable implement Testable
{
    Symbol variable;
....
}

(Not that it is a good idea, but is something I probably something saw a dozen of times).

its the fact that someone built an entire function around a builtin operator that uses said operator.

That said, if the interpretation of most people here is lol, a function build around an operator is bad code, then, well, it is time for me to leave.

edit: typo

1

u/Mr2-1782Man Jun 24 '20

Its not about being build around an operator, that's no problem. Its about replacing the operator with function that uses the operator. And anyone that writes an interface like that is already writing bad code to begin with. If you're interface has something like "isTrue" you've got bad architecture, or you've gone OOP so far that it doesn't make sense anymore.

-5

u/madanaman Jun 23 '20

Hahaha. Can't stop laughing 😂😂😂 Only reason for this code's existence could be that it's developed by a newbie who have learnt functions but skipped the chapter on datatypes.

8

u/[deleted] Jun 23 '20

found the CS1 kid that thinks they know everything

4

u/garfield1147 Jun 23 '20

As someone who is reviewing more code then I write, I smirk rather than laugh.

The only good thing with this is that it signals to the rest of the team, of there is such, to closely watch this persons code for more beginner mistakes.

On a tangent, we have all been there, though, but seeing lots of things like this might have a negative impact on your mind about the futility of quality and trust in people. I try to involve new devs into the reviews as soon as possible.