Really simple question, I just wanted to know if there was a way to write if/else statements with fewer characters, for example I can create an if statement with either:
if (season == "autumn") {
tree.gotoAndStop ("brown leaves");
}
or:
if (season == "autumn") tree.gotoAndStop ("brown leaves");
This uses much less space and makes my code look much prettier. With an if/else statement my options seem to be either:
if (season == "autumn" || season == "winter") {
tree.gotoAndStop ("brown leaves");
} else {
tree.gotoAndStop ("green leaves");
}
or:
gotoAndStop((season == "autumn" || season == "winter")
? "brown leaves" : "green leaves");
Though the second approach isn't always ideal. Do you know any alternatives?
As far as writing your code in a terse manner, you can use all of the following techniques to manually minify your code, but this is a terrible design decision and will likely lead to headaches and/or bodily harm in the future. Don't say I didn't warn you.
if-else:
if (foo) {
bar();
} else {
baz();
}
becomes:
foo?bar():baz()
if:
if (foo) {
bar();
}
becomes:
foo&&bar();
if-not:
if (!foo) {
bar();
}
becomes:
foo||bar();
if with multiple statements:
if (foo) {
bar();
baz();
fizz();
buzz();
}
becomes:
foo&&(bar(),baz(),fizz(),buzz());
Related
I'm wondering if any programming language has an operator like so (ALWAYS is a placeholder--I'm asking what language has something like ALWAYS)
if a
doAStuff()
else if b
doBStuff()
ALWAYS
//runs if a or b is true
win()
else
doElse()
Basically, the opposite of else. It runs if something else in the statement ran.
logically, it would be like this
always = true
if a
doA()
else if b
doB()
else
always = false
doElse()
if always
win()
Does any language have that logic built into a keyword, such as ALWAYS from the first example?
Not really 'language-agnostic'. More like 'find-my-language'. With Forth and Lisp you can add such a construct naturally to the language, and it will work just like existing constructs. I'm not aware of any language that has it by default. If you have a less extensible language than Forth or Lisp, then the natural ways to do this are to use a local function (if you have first-class functions) or to set a flag as you show, or else to factor the code such that both conditions can be treated as pairs without a lot of repetition.
So, in JavaScript:
;(function() {
function both() { win(); more stuff, potentially }
if (a) { doA(); if (b) both() }
else if (b) { doB(); if (a) both() }
else neither()
})()
At upon reading that, it should be clear that the 'both' case is never going to happen in that second block. So this simplifies to:
;(function() {
function both() { win(); more stuff, potentially }
if (a) { doA(); if (b) both() }
else if (b) doB()
else neither()
})()
Which doesn't seem worth the effort. So it seems even less worth a language feature. Why not go further and write this?
if (a) { doA(); if (b) { win(); more stuff, potentially } }
else if (b) doB()
else neither()
If b is an expensive test, just save the result of it. If b must not be tested before a, save both results. Obviously, both tests must always be run anyway.
;(function() {
var a = testA(),
b = testB()
... as above ...
})()
As for the last option, "factor the code such that both conditions can be treated as pairs", what you're looking for is:
if (a && !b) doA()
if (!a && b) doB()
if (a && b) { doA(); doB(); win() } // or no doB() if you really want that
if (!a && !b) neither()
With else if if you like. I'd prefer this option actually in a pattern-matching language. Mercury will even throw an compile-time error if you forget one of the four possible outcomes.
Not sure if this is what you're looking for, but a simple do-while loop will ALWAYS run at least once in Java.
When I need a conditional to determine whether a block before or after a statement gets executed, this always leads to repeated code. I either end up with evaluating the condition twice, or repeating the block of code.
Even if this block is just a single function call, it doesn't exactly add to readability.
if( condition ) {
BLOCK-A
}
BLOCK-B
if ( !condition ) {
BLOCK-C
}
or
if( condition ) {
BLOCK-A
BLOCK-B
} else {
BLOCK-B
BLOCK-C
}
Is there a clearer way to structure code like this?
Of your options I would do it this way:
if( condition ) {
BLOCK-A
BLOCK-B
} else {
BLOCK-B
BLOCK-C
}
This will avoid evaluating the condition multiple times as you state in your question.
However, ideally I would try and avoid this kind of structuring all together as it couples the code up and can make changes further down the line difficult. Someone could change something in BLOCK-B for example in one place and not in another. Possibly moving Block-B into it's own function/method etc would be prudent.
Personally I would do something like this
function BlockB()
{
//code from block b
}
function FirstCondition()
{
//BLOCK-A code
BlockB()
}
function SecondCondition()
{
//BLOCK-C code
BlockB()
}
if( condition ) {
FirstCondition()
} else {
SecondCondition()
}
It sounds like BLOCK-B has two similar uses. Consider abstracting it out into its own area
function D {
BLOCK-B
}
if( condition ) {
BLOCK-A
function D
} else {
function D
BLOCK-C
}
I'm working on a match-3 style puzzle game using Flixel, and so I'm working on checking each row and column to see if there is a match at any given time. However, I have 6 different pieces (as of right now) that are active, and each piece is identified by an integer. Given that, I can check, for each and every single piece, by doing something like this:
public function matchingCheck():void
{
if (piecesArray[0][1] == 1 && piecesArray[1][1] == 1 && piecesArray[2][1] == 1) {
FlxG.log("Yay!");
}
}
However, this is rather unwieldy and would basically cause way too much repetition for my liking.
At the very least, I would like to be able to check if the values in these arrays are equal to one another, without having to specify which value it is. At the very best, I'd love to be able to check an entire row for three (or more) adjacent pieces, but I will settle for doing that part manually.
Thanks for your help!
EDIT: Nevermind, my edit didn't work. It was just checking if piecesArray[2][1] == 1, which makes me a sad panda.
EDIT 2: I've selected the correct answer below - it's not exactly what I used, but it definitely got me started. Thanks Apocalyptic0n3!
You could cut down on that code a little bit by using another function
private function checkValid( arrayOfItemsToCheck:Array, value:* ):Boolean {
for ( var i:Number = 0; i < arrayOfItemsToCheck.length; i++ ) {
if ( arrayOfItemsToCheck[i] != value ) {
return false;
}
}
return true;
}
Then you just do this in your if statement:
if ( checkValid( [ piecesArray[0][1], piecesArray[1][1], piecesArray[2][1] ], 1 ) ) {
FlxG.log("Yay!");
}
That does assume all items need to be equal to 1, though. It's still a lot of code, but it cuts out one set of "= 1 &&" for each check.
How about something like this which would tell you both if a match existed and what match it was:
public function checkForMatch():void{
var rows:int = piecesArray.length;
for(var i:int=0; i<rows; i++){
var match:int = checkRow(piecesArray[i]);
if(match > -1) {
FlxG.log("Yay you matched " + match);
}
}
}
private function ckeckRow(row:Array):int{
if(row[0] == row[1] == row[2]){
return row[0];
}
return -1;
}
please
how to fix this AS3 function ?
thank you
function dispari(numero:int):Boolean;
{
//check if the number is odd or even
if (numero % 2 == 0)
{
returns false;
}
else
{
returns true;
}
}
ERROR:
1071: Syntax error: expected a definition keyword (such as function) after attribute returns, not false.
Why do you have a semi-colon (;) at the end of your function statement? I don't do any AS3 coding but it doesn't look right, and a cursory glance at a few samples on the web don't have it there.
I suspect that may be what's causing your problem. Try this instead:
function dispari(numero:int):Boolean
{
//check if the number is odd or even
if (numero % 2 == 0)
{
return false;
}
else
{
return true;
}
}
I've also changed the return statements to match what every other piece of AS3 does to return values (thanks, #Herms, forgot to mention that :-)
Pax is correct with there answer, but you can simplify it by just returning the result:
function dispari(numero:int):Boolean
{
return (numero % 2 != 0);
}
What is the better practice of the following two switch/case statements?
Is there an easier way (less code) to do this?
switch (myValue)
{
case 1:
{
methodFor1();
break;
}
case 2:
case 3:
{
methodFor2or3();
if (myValue == 2)
methodFor2();
if (myValue == 3)
methodFor3();
break;
}
}
...or...
switch (myValue)
{
case 1:
{
methodFor1();
break;
}
case 2:
case 3:
{
methodFor2or3();
switch (myValue)
{
case 2:
{
methodFor2();
break;
}
case 3:
{
methodFor3();
break;
}
}
break;
}
}
switch (myValue)
{
case 1:
methodFor1();
break;
case 2:
methodFor2or3();
methodFor2();
break;
case 3:
methodFor2or3();
methodFor3();
break;
}
Why all the hassle just to avoid repeating methodFor2or3() once?
One more alternative:
switch (myValue)
{
case 1:
{
methodFor1();
break;
}
case 2:
{
methodFor2or3();
methodFor2();
break;
}
case 3:
{
methodFor2or3();
methodFor3();
break;
}
}
Since functions are first class objects in actionscript3, you could build a hash of values to functions, like so:
var myDict:Dictionary = new Dictionary();
myDict[1] = methodFor1;
myDict[2] = methodFor2;
function handleStuff(myVal:Number):void{
var myFunction:Function = myDict[myVal];
myFunction();
}
hope this helps!
In my programming of switch statements, I aim for making each case have at most one line of code + a break;. This is because switch can quickly get big and complicated, and my brain isn't good at complicated.
So, in your case, I would write:
switch (myValue)
{
case 1:
{
methodFor1();
break;
}
case 2:
{
methodFor2();
break;
}
case 3:
{
methodFor3();
break;
}
}
and then make methodFor2 and methodFor3 each call methodFor2or3.
If there is only one (fairly simple) line in common between the two cases (as the function call in your example), then I prefer to double that line just for the sake of better readability. Otherwise, it's a matter of taste. I tend to prefer if conditions inside the case statements, because that way you can't confuse the various levels.
How about something more like:
var method:String = "methodFor" + String(value);
this[method]();
if (value == 3) methodFor2or3();
You might think of splitting out the or3 call if it's simpler code you want:
switch (value) {
case 1: methodFor1(); break;
case 2: methodFor2(); break;
case 3: methodFor3(); break;
}
if (value == 2 || value == 3) methodFor2or3();
When you're dealing with programming flow of control issues, "less code" isn't really the attribute you want to optimize on. It's far better with structural issues to bend your code towards being simple and readable.
So for the above, the first option isn't bad, although the 'flow-through' case for 2 can easily be missed. Better is to just do the parent switch on a 1 or 2, then in the second case call another function that handles the sub-cases (formally 2 and 3), and make this driven by a different (sub-case) variable (to insure that you're not overloading the 'meaning' of the initial 'value' variable.
Philosophically, all three cases are part of the same switch, OR they are not. If they are, then they should be treated equally (and indistinguishably from each other). If they are not, then they should be driven by two separate variables and handled in two separate functions. Trying to save 'bandwidth' by combining them complicates thing unnecessarily.
Paul.
I am answering assuming that you know the example case you gave is contrived and is better written in other ways. If you just want to know if it's best to nest switches or to use if-else within a switch, it totally depends on taste and the individual situation.
In my opinion, the fact that your block is inside a switch makes no difference. If the logic would be better served by a switch, use a switch (nested or not). If it would be better served by an if-else, use that.