Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why write functions :void?

I am in the habit of writing:

function functionName():void
{

}

If my function has no return type (":void"), however, I notice that my function will work if I write:

function functionName()
{

}

...without specifying the return type. Why is it considered good form to show the return type as :void?

like image 946
redconservatory Avatar asked Apr 09 '26 08:04

redconservatory


2 Answers

Because it follows the strict use of data typing, if there is a :void return type, the compiler could warn on non void returns. (although the standard compiler does not.)

Without it the function declaration is semantically ambiguous.

(edit: updated for clarification, code is for us humans to be able to read, if readability and semantic richness were not all that important, we'd all be coding in binary, using a flip switch.)

like image 86
ocodo Avatar answered Apr 12 '26 03:04

ocodo


The long and short of it is that every object in Flash has a data type. This can be a native data type, like "String" or "Number" or "Array" or "int", or it can be a custom data type, like "MyCustomClass" or "ICustomInterface".

If Flash knows the data type of an object, it's able to work with it much more quickly because it knows exactly what methods and properties that object does or does not have. This is why, for instance, you can iterate through a Vector much more quickly than you can iterate through an Array - a Vector forces every element to be of the same type, which means that the runtime doesn't have to sit there and type-check every single item in your Vector. It just knows, for instance, that every item in the vector implements the IWhatever interface, and that's all it cares about.

So, this is where :void comes in. In AS3, functions are also objects. A function can return absolutely anything - so you assign a type declaration to the function to tell the Flash Player that when an object is returned from that function it is of a particular type.

There's another reason, which has been touched on above. When you declare a return type, your function is type safe. If you declare :int and try to return a String, you'll get an error. This is good - that error tells you that your code is not behaving the way you expect it to.

When we declare functions to be :void, then, what we're telling flash is that no return is expected from this function. If the function should happen to return anything at all, it'll throw an error.

I hope that helps! :)

like image 33
Myk Avatar answered Apr 12 '26 03:04

Myk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!