r/badcode • u/bausscode • Jan 17 '19
other language Writing functions with conditions without using "if" statements
https://run.dlang.io/is/jfCECL
68
Upvotes
r/badcode • u/bausscode • Jan 17 '19
29
u/Kidiri90 Jan 17 '19 edited Jan 17 '19
No conditionals, not even ternary operators, though I don't like the try-catch block. Sadly, it's needed to stop the divide by zero errors you'll get when x=y. I'm trying to think of a way to get rid of this problem.
EDIT: figured it out:
Not a single conditional in sight, and not phony conditionals by using try-catch blocks.
9
u/bausscode Jan 17 '19
Basically the two functions "addOrMul1()" and "addOrMul2()" does the exact same thing.
However "addOrMul2()" does not use any if statements to accomplish the same task. Instead it's an ugly mess of hacking tricks that makes the compiler treat it like conditional statements.
Terrible code that works.
11
u/[deleted] Jan 17 '19
This isn't bad code. It's a bad example, but this is how you write good, declarative Object Oriented software.
3
u/Achereto Jan 17 '19
There are actually good reasons to avoid
ifas often as possible (Smalltalkdoesn't even haveifas a keyword). There seems to be a direct correlation between the number ofifin your code and the number of bugs you have.Talk "If considered harmful": https://www.youtube.com/watch?v=z43bmaMwagI
1
u/OptiPanda_ wicked Jan 17 '19
if (x > y) return x * y; Return x + y;
Can be refactored as this : return (x>y)? x*y : x+y;
1
u/Pocciox Jan 17 '19
When I was in highschool our professor gave us an homework where we had to code a PHP conditional output without using if, while, for, or any flow control instruction. The solution was:
$aVariable = 1 // set it to 2 for the other output
$foo2 = "condition2"; $foo1 = "condition1";
echo $foo$aVariable;
Sorry for poor formatting I am on mobile
1
u/Elronnd Jan 21 '19
Why not just:
-6
u/[deleted] Jan 17 '19
They told me that ifs and switches are bad. BTW, how to comapre two string in JAVA? == doesent seem to work, plese help
2
u/[deleted] Jan 17 '19 edited Jan 17 '19
[removed] — view removed comment