as3 - what's the difference when you put () at the end? - actionscript-3

if you say for instance
instance:Instance = new Instance();
or
instance:Instance = new Instance;
Why does it matter? It's empty anyways so.

ActionScript's compiler running in strict or standard mode allows for that syntax for instantiating an object. The class' nullary (zero arity) constructor is called either way and thus the resulting object is the same...
Most of Actionscript's language syntax is derived from ECMAScript so if you are looking for someone to blame... ;-)
A lot of languages enforce the () syntax to visual distinguish function/methods vs. properties but that is strictly in the language designer's hands.... Personally I use the () syntax as a visual cue as I work in a few different languages and all the others require it...

Related

Can I use the <> syntax in AS3 for anything other than Vector.<T>?

I've been learning a fair bit of C# lately and noticed that the <> syntax is used a lot, eg:
Content.Load<AssetType>("asset name");
The only place I've seen this used in AS3 is when using Vectors:
var enemies:Vector.<Enemy> = new Vector.<Enemy>();
Can I implement use of this syntax myself somehow in ActionScript 3? For example, I may want my own method similar to Content.Load().
The syntax you're referring to is called generics, and Vector is the only way they can currently be used in AS3.
Here is a link to a related question about AS3's generics, why you can't create your own.
Hope this helps!
The only other place where the angled braces are used (as far as I know) is for declaring inline XML:
var myXML:XML = <rootNode><dataNode>What's up?</dataNode></rootNode>;
Which is horrible programming practice. I don't believe there is any way to extend AS3 in the manner you describe, as it is only possible to create class extensions, not entirely new language syntax.
As far as I know, the Realaxy editor provides generics through a language extension. The dev talks about it here (see the comments)
The only problem is that it ties you to the editor.
That said, you could also probably fake it through reflection, or just doing your own runtime checking. Not a perfect solution though

Is it possible to write an AS3 library with Haxe that uses type parameters?

First a little background: I'm looking for a way to create a "collection" library that abstracts the Flash Player version based implementation (Vector on FP10, Array on FP9) away from the calling code. I've already written a small AS3 lib doing that but...
...the performance is bad (especially because of two levels of indirection and the runtime type checks on the Array implementation)
...the code is ugly (since Vector types need to be defined at compiletime I needed a factory returning concrete Vector instances based on an Enum that contains only the supported types)
I'm currently looking into Haxe as a possible solution since it supports type parameters and is able to compile to various Flash Player versions (and apparently compiles into mmore optimized bytecode).
Now, my question is: Is there a way to write a library in Haxe that can be used like this in AS3 code
var foo:IMyInterface = new MyImplementation(int);
var bar:IMyInterface = new MyImplementation(getDefinitionByName("my.package.MyClass"));
with IMyInterface exposing the required methods (push, pop, ...)?
The basic idea is that I want to provide the type information at runtime and get a typesafe Flash Player version independent "collection" for use in the calling code without having to bother with conditional compilation fragments all over the place.
Can Haxe do something like that and if yes, how can I make it work?
There's an opportunity in Haxe to override native classes (e.g. int) in Haxe. take a look at the Metadata manual. Metadata has been added in version 2.06.
As for analogue of getDefinitionByName() method. Take a look at resolveClass() method of the Type class.

What's the difference between closures and traditional classes?

What are the pros and cons of closures against classes, and vice versa?
Edit:
As user Faisal put it, both closures and classes can be used to "describe an entity that maintains and manipulates state", so closures provide a way to program in an object oriented way using functional languages. Like most programmers, I'm more familiar with classes.
The intention of this question is not to open another flame war about which programming paradigm is better, or if closures and classes are fully equivalent, or poor man's one-another.
What I'd like to know is if anyone found a scenario in which one approach really beats the other, and why.
Functionally, closures and objects are equivalent. A closure can emulate an object and vice versa. So which one you use is a matter of syntactic convenience, or which one your programming language can best handle.
In C++ closures are not syntactically available, so you are forced to go with "functors", which are objects that override operator() and may be called in a way that looks like a function call.
In Java you don't even have functors, so you get things like the Visitor pattern, which would just be a higher order function in a language that supports closures.
In standard Scheme you don't have objects, so sometimes you end up implementing them by writing a closure with a dispatch function, executing different sub-closures depending on the incoming parameters.
In a language like Python, the syntax of which has both functors and closures, it's basically a matter of taste and which you feel is the better way to express what you are doing.
Personally, I would say that in any language that has syntax for both, closures are a much more clear and clean way to express objects with a single method. And vice versa, if your closure starts handling dispatch to sub-closures based on the incoming parameters, you should probably be using an object instead.
Personally, I think it's a matter of using the right tool for the job...more specifically, of properly communicating your intent.
If you want to explicitly show that all your objects share a common definition and want strong type-checking of such, you probably want to use a class. The disadvantage of not being able to alter the structure of your class at runtime is actually a strength in this case, since you know exactly what you're dealing with.
If instead you want to create a heterogeneous collection of "objects" (i.e. state represented as variables closed under some function w/inner functions to manipulate that data), you might be better off creating a closure. In this case, there's no real guarantee about the structure of the object you end up with, but you get all the flexibility of defining it exactly as you like at runtime.
Thank you for asking, actually; I'd responded with a sort of knee-jerk "classes and closures are totally different!" attitude at first, but with some research I realize the problem isn't nearly as cut-and-dry as I'd thought.
Closures are very lightly related to classes. Classes let you define fields and methods, and closures hold information about local variables from a function call. There is no possible comparison of the two in a language-agnostic manner: they don't serve the same purpose at all. Besides, closures are much more related to functional programming than to object-oriented programming.
For instance, look at the following C# code:
static void Main(String[] args)
{
int i = 4;
var myDelegate = delegate()
{
i = 5;
}
Console.WriteLine(i);
myDelegate();
Console.WriteLine(i);
}
This gives "4" then "5". myDelegate, being a delegate, is a closure and knows about all the variables currently used by the function. Therefore, when I call it, it is allowed to change the value of i inside the "parent" function. This would not be permitted for a normal function.
Classes, if you know what they are, are completely different.
A possible reason of your confusion is that when a language has no language support for closures, it's possible to simulate them using classes that will hold every variable we need to keep around. For instance, we could rewrite the above code like this:
class MainClosure()
{
public int i;
void Apply()
{
i = 5;
}
}
static void Main(String[] args)
{
MainClosure closure;
closure.i = 4;
Console.WriteLine(closure.i);
closure.Apply();
Console.WriteLine(closure.i);
}
We've transformed the delegate to a class that we've called MainClosure. Instead of creating the variable i inside the Main function, we've created a MainClosure object, that has an i field. This is the one we'll use. Also, we've built the code the function executes inside an instance method, instead of inside the method.
As you can see, even though this was an easy example (only one variable), it is considerably more work. In a context where you want closures, using objects is a poor solution. However, classes are not only useful for creating closures, and their usual purpose is usually far different.

Using functional language concepts with OO - is there a language?

I was recently thinking how I'm not always using the beautiful concepts of OO when writing Pythonic programs. In particular, I thought I'd be interested in seeing a language where I could write the typical web script as
# Fictional language
# This script's combined effect is to transform (Template, URI, Database) -> HTTPOutput
HTTPOutput:
HTTPHeaders + Maintext
Flags: # This is a transform URI -> Flags
value = URI.split('?').after
refresh = 'r' in value
sort = /sort=([a-z])/.search(value)
HTTPHeaders: # This is a transform Flags -> HTTPHeaders
'Content-type:...' + Flags.refresh ? 'Refresh: ...' : ''
Maintext:
Template.replace('$questions', PresentedQuestions [:20] )
Questions:
(Flags.sort = 'r') ? RecentQuestions : TopQuestions
PresentedQuestions:
Questions % '<h4>{title}</h4><p>{body}</p>'
RecentQuestions:
Database.Questions . sort('date')
TopQuestions:
Database.Questions . sort('votes')
See what happens? I am trying to make as many objects as possible; each paragraph declares something I call transform. For example, there is a transform HTTPHeaders. In an imperative language that would be a declaration of class, object and function combined:
class HTTPHeaders_class
{
public char* value
HTTPHeaders_class()
{
value = ... + Flags.refresh ? + ... // [1]
}
}
class Flags_class
{
public char* flagstring;
public bool refresh;
...
Flags_class()
{
value = ... /* [3] */
refresh = ...
}
}
Flags = new Flags_class (URI)
HTTPHeaders = new HTTPHeaders_class (Flags) // [2]
However, I want to have no way to specify that an object should change unless the inputs from which the objects is made change; and no way to have side effects. This makes for a drastic simplification of language. I believe this means we're doing a functional programming ("a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data").
I certainly try to use things like Python classes, M-V-C framework and Django (thanks to the answer), but I don't think they have the concepts above and below.
Each object has a value field that can be referred just by writing the class name.
If HTTPHeader is referred somewhere, this means that a static, unchangeable object HTTPHeader is created as soon as possible. All references to HTTPHeader then refer to this object.
Suppose I want to repeat the program with the same URI object while the interpreter is still in memory. Since Flags depends only on URI and HTTPHeaders only on Flags, those are not recalculated. However, if Database is modified, then Questions need to be recalculated, and thus the HTTPOutput may change too.
The interpreter automatically deduces the correct sequence of initializing the classes. Their dependency must form a tree for that to happen, of course.
I believe this will be a useful models for programs like web scripts where there are no side effects. Is there a useful language where one writes program similar to this already?
If you really want to delve into web application development with Python, then look at Django. You are better off using a MVC architecture in this case and Django does a very nice job of supporting MVC applications.
What you are probably interested in is more of a Declarative programming approach than a functional one. Functional programming is more concerned with mapping an input to an output as a pure (mathematical) function. The declarative approach is all about stating what should happen instead of how to do it.
In any case, dig into Model-View-Controller and Django. You will probably find that it fits the bill in a completely different manner.
Take a look at F#. It is specifically designed as a functional language (based on OCaml) with OO support utilizing the .NET stack.
I don't think it's exactly what you are looking for but Scala tries to integrate OO and functional features under a common language.
Your code looks like a DSL for web applications and Sinatra is such a DSL. Sinatra does not do exactly what you do there but it's in the same ballpark. http://www.sinatrarb.com/ - it's written in Ruby but hey, let's all be friends here in dynamic languages land.
This actually feels very much like Haskell, except that you're not using pure functions here. For example, Flags doesn't have the URI passed into it; URI is a separate definition that is presumably not producing the same URI every time it's called, and so on.
For URI to be a pure function, it would have to have a parameter that would give it the current request, so that it can always return the same value for the same inputs. (Without any parameters to work on, a pure function can only return the same result over the life of a closure.) However, if you want to avoid explicitly giving URI a parameter every time, this can be done with various techniques; we do this with monads in Haskell.
It seems to me that the style of programming you're thinking of might be based on "combinators," having small functions that are glued together inside a framework to produce a large, complex function that does the overall processing.
I see my favourite language has not been mentioned yet, so I'd like to jump in and suggest Dyalog APL as a language for 100% function programming. APL has a looong history and was developed when there was no Internet - but Dyalog is the most active provider of APL-Implementations and they also have a fully function webserver that is available free of charge. (The interpreter is also available free of charge for non-commercial use.)

What is the benefit of explicitly naming getters and setters as "get..." and "set..."?

Does this rankle anyone else out there? I would much rather see:
block.key(newKey); // set the key for this block
and
testKey = block.key(); // look up the key for this block
than
block.setKey(newKey); // set the key for this block
testKey = block.getKey(); // look up the key for this block
First, the "set" and "get" are redundant (and hence add noise reducing the readability). The action (set/get) is defined by the syntax of each statement. I understand the overloading. In fact, using the same exact identifier reinforces that these are the same property of the object. When I read "getKey()" and "setKey()" I may not be so sure.
Second, if "get" and "set" are to be strictly interpreted as setter and getter, then if other semantic associated with setting/getting a value, side effects for example, will be surprising.
I suppose this bias comes from my Smalltalk background, but in a world where polymorphism works just fine, wouldn't we be better off without the "get" and "set" sprinkled everywhere? Just think of how much more code we could type if we didn't have to type those three letters over and over again?! (tongue somewhat in cheek)
Anyone out there feel the same way?
The designers of C# apparently agree, and the 'C#' tag outnumbers the next most popular language by 2:1 on StackOverflow. So I suspect you're preaching to the choir.
Several languages have different ways of handling getters and setters. In Java you have getName and setName, in Qt you have name and setName. I prefer the Java way for these reasons:
What if you have a function that is called drive? Does it cause your class to drive, or does it set/get a drive?
With suggestions turned on, you can type get, and then get all the getters. This is very useful if you don't remember the name of a getter you need.
Building on reason one, it separates the functions into different groups. You have the functions that do something, they don't start with get or set (though maybe they should start with do?). Then you have the functions that get a property, and they all start with get. Then you have the functions that set a property, and they all start with set.
For me, get and set prefixes make my brain do less work when reading code. When used consistently, get/set methods make it easier to grep a header, possibly making the class easier to learn & use. I spend a disproportionately large amount of time reading code vs. writing code, so the extra characters for get and set are fine by me.
The Java language currently doesn't have properties, so the getter / setter syntax has become the de-facto standard. If your writing Java code, you'll be well served to use the Java convention. This isn't just so other programmers can read your code, but more importantly hundreds of other Java frameworks are built to handle objects supporting Java Bean style getters / setters.
For example, in the Velocity templating engine, you could write something like:
The answer is $block.key
The above will attempt to invoke:
block.getkey();
block.getKey();
If you've defined block.getKey(), then all will work fine. Generally it's best to follow the conventions of the language.
Prefixing accessors with "get" and mutators with "set" is a practice that varies from language to language, and seems to be mostly prevalent in Java. For example:
In Python, you have the concept of properties, and so an accessor might look like obj.foo and a mutator might look like obj.foo = bar (even though methods are called behind the scenes). Similar concepts exist in languages such as Ruby. So in a lot of languages, calls to accessors and mutators look like direct "calls" to instance variables, and you never see anything like "setFoo" or "getFoo".
Languages such as Objective-C discourage the practice of prefixing accessors with "get", so in Objective-C you'd see calls like [obj foo] and [obj setFoo:bar].
I never liked the practice of prefixing accessors in Java with "get", either, but I do see the merit in prefixing mutators with "set". That said, since the prevailing practice is to prefix with "get"/"set" in Java, I continue the trend in my own code.
In general property names should be nouns whereas method names should be verbs, so the property in the above example would be called 'driver' and the method would be 'drive'. There will of course be cases where there is overlap but in general this works and makes the code more readable.
In C++ I just use overloading
int parameter() const { return m_param }
void parameter(int param) { m_param = param; }
Yes the get/set in java is essentially a workaround a problem in the language.
Comparing it to c# properites
http://www.csharp-station.com/Tutorials/Lesson10.aspx
Or python
http://blog.fedecarg.com/2008/08/17/no-need-for-setget-methods-in-python/
I think this is one of biggest failings of java.
C# getters and setters are "first class" entities and don't resemble function calls syntactically (though any arbitrary code can run in the context of an accessor).
I only use get/set in languages that force me to, like Objective-C.
You can easily search your codebase for references to getDrive() or setDrive(). If your method is just named 'drive', you will get many more false positives when searching.
Hear, hear.
I really like special notation for getters and setters. CLU did this best:
Using p.x in an expression was equivalent to the call get_x(p).
Using p.x := e (assignment) was equivalent to the call set_x(p, e).
If the interface for object p didn't export get_x or set_x, you were prevented from doing the corresponding operation. Simple.
Let's hear it for syntactic sugar!