12. Feb, 2009
hello again!
Yesterday I wrote some code again and had to check if a String is null or not. The check was performed in a for-loop.
Below is some example code:
public var arrToFill:Array = [];
[... some more code here ...]
private function foo():void
{
var i:uint;
for( i = 0; i < 10; ++i)
{
if(!arrToFill[i])
{
arrToFill[i] = '';
}
}
}
This function was called different times and I wondered, that the if-statement returned false everytime.
For me it was theoretically correct that an Array-Element with a value of ” is not empty, because ” is an empty String for me, but it is something.
ActionScript3 doesn’t work like that, so for AS3 a String with a value of ” is equal to null or 0.
Conclusion:
If you have code like this and want to preallocate an element, just set it to 1. Then you can do a simpy
and everything would be fine.
6. Feb, 2009
I thought about doing an extra section called ‘TIDY UP YOUR CODE’.
From time to time I will post some tips how you can write reader-friendly code.
So Let’ start with the first topic: if – elseif – elseif – elseif – else
Have you ever seen something like this ?
if(expressionA)
{
.. do something ..
}
elseif(expressionB)
{
.. do something else..
}
elseif(expressionC)
{
.. do something else..
}
elseif(expressionD)
{
.. do something else..
}
else
{
.. do something else..
}
Code like this is hard to read, don’t you agree with this?
TIDY IT UP! Use a switch instead:
switch(true)
{
case expressionA:
{
.. do something ..
}; break;
case expressionB:
{
.. do something else ..
}; break;
case expressionC:
{
.. do something else ..
}; break;
case expressionD:
{
.. do something else ..
}; break;
default:
{
.. do something else ..
}; break;
}
In my opinion this is great :-}
6. Feb, 2009
Hello out there!
Today I learned how to check a lot of statements in one expression, but without having unreadable code like that:
if(this.strChar == 'a' || this.strChar == 'b' || this.strChar == 'c')
{
.. do something ..
}
What you can do instead is creating an unnamed Array, push the values into it and then check if the Array contains one of those values.
Let’s see:
package
{
pubilc class foo
{
public function foo(strChar:String = 'default'):Boolean
{
if(['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'default'].indexOf(strChar) >= 0)
{
return true;
}
return false;
}
}
}
i suppose that most of the code should be understandable to you, but let’s take a look at the if-statement:
if(['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'default'].indexOf(strChar) >= 0)
You could also use the following code with the same result:
var arrStringNumbers:Array = new Array();
arrStringNumbers.push('one', 'two', 'three' /*and so on... */);
if(arrStringNumbers.indexOf(strChar) >= 0) // give me the index of strChar (if arrStringNumbers does not contain strChar, we get -1 as result, so the if-statement is false)