☰
d2jsp
Rules
Help
Forum Gold FAQ
Live Streams
Photo Gallery
Hourly Raffle
Ladder Slasher
Log In
Register
Log In
Register
Account Recovery
Resend Validation Email
d2jsp Forums
>
Off-Topic
>
Computers & IT
>
Programming & Development
> Can Someone Explain This Code
Add Reply
New Topic
New Poll
Views: 701
Replies: 9
Track Topic
ferf
Member
Posts: 31,293
Joined: Mar 25 2009
Gold
:
0.00
#1
Apr 25 2017 06:28am
Code
isCar = true;
boolean wasCar = isCar ? true : false;
if(wasCar)
System.out.println("wasCar is true");
Particularily this line:
boolean wasCar = isCar ? true : false;
nuvo
Member
Posts: 3,197
Joined: May 4 2013
Gold
:
1,457.00
#2
Apr 25 2017 06:39am
it's ternary operator. Equivalent to writing
Code
if (isCar) {
wasCar = true;
} else {
wasCar = false;
}
Mastersam93
Member
Posts: 36,123
Joined: Jul 18 2008
Gold
:
2,407.00
#3
Apr 25 2017 06:44am
I hate ternary operators. Imo not as readable and I'm sure the compiler doesn't care if it's a ternary operator or if/else.
nuvo
Member
Posts: 3,197
Joined: May 4 2013
Gold
:
1,457.00
#4
Apr 25 2017 06:49am
It has its places, and you'll start to appreciate it as soon as you start working with language that doesn't support them :/ (eg. golang)
eg. it's super useful when using any kind of templating for any reason (rendering website, filling email or document ...)
Code
<p class="<%= activate ? "active" : "disabled" %>">foo</p>
This post was edited by nuvo on Apr 25 2017 06:52am
ferf
Member
Posts: 31,293
Joined: Mar 25 2009
Gold
:
0.00
#5
Apr 25 2017 06:50am
hmm ok thanks guys, makes sense
one question though
wouldn't this alone:
boolean wasCar = isCar ? true : false;
^make it so if isCar = true, wasCar = true?
you don't need if (wascar)?
nuvo
Member
Posts: 3,197
Joined: May 4 2013
Gold
:
1,457.00
#6
Apr 25 2017 06:52am
This whole code is pretty useless and you could
Code
wasCar = isCar
and it would do exactly the same, and then wasCar would still be useless as you say.
waraholic
Member
Posts: 1,039
Joined: Jul 8 2008
Gold
:
1,939.50
#7
Apr 25 2017 04:57pm
They are a very good tool to know how to use. There are many places you can use a ternary in place of an if/else and make the code more maintainable, but don't overdo it and nest them.
ASBands
Member
Posts: 6,953
Joined: Sep 27 2003
Gold
:
518.50
#8
Apr 25 2017 07:15pm
Ternaries are great when you need an expression instead of a statement, but they're losing relevancy as more programming languages are embracing the "everything is an expression" philosophy. Take Rust, for example:
Code
let res = if something { value1 } else { value2 };
Almost every language has a conditional expression of some sort.
This post was edited by ASBands on Apr 25 2017 07:16pm
Oceans334
Member
Posts: 73
Joined: Dec 18 2015
Gold
:
Locked
#9
May 3 2017 09:57am
:D
ryota
Member
Posts: 12,080
Joined: May 3 2017
Gold
:
Locked
Trader:
Scammer
#10
May 3 2017 03:12pm
Messy code
Go Back To
Programming & Development
Topic List
Add Reply
New Topic
New Poll
© 2003-2024 d2jsp
Contact