does static methods need to use static properties? - actionscript-3

I am using as3. Just a simple question.
If I created a static method. say I decide to call on other methods within that static method. Do those methods I call on need to be static as well? what If I used some of the properties. Not to store data permanently, but just within that process. Do those properties need to be static ??

Yes. If anything is called static that means that it is related not to the current instance of the class but to the whole class therefore it must act instance-independent, e.g. use other static fields and methods if needed.

No, they do not. You can use any type of variable/method from within a static method, including, of course, local variables. However, there is no concept of "this" in a static method, since the method is not being executed on an instance, but on the class itself. Therefor, the following (inside a class declaration) is illegal:
public var myInstanceVariable : int;
public static function myStaticMethod() : void
{
// Illegal:
myInstanceVariable = 1;
// Illegal (same as above, "this" is implicit):
this.myInstanceVariebl = 1;
// This however is legal (local variable):
var localVal : int = 1;
}
The references to myInstanceVariable above are illegal because that variable is an instance variable, which is not accessible to the static method. Because static methods are not executed on an instance in the first place, the "this" special variable is not valid.
If you wanted to, you could keep a static reference to an instance, and execute methods on said instance. That's the key idea behind the common singleton pattern.
private static var _INSTANCE : MyClass;
public static function myStaticFunction() : void
{
_INSTANCE.doSomething();
}
Here, the _INSTANCE variable can be referenced from the static method, because the variable itself is declared as static.

To avoid confusion, there are actually answers to both the questions you asked:
Do method calls within a static method need to be static? Li0liQ answered this.
Do variables used within a static method need to be static? richardolsson answered this.
To summarize, within a static method, you can only access static variables and methods EXCEPT if you define local variables within the scope of the static method.
private var instanceVar : MyClass;
private static var staticVar : MyClass;
public static function myStaticFunction() : void
{
// Illegal, instance variable
instanceVar = new MyClass( 1 );
// Illegal, method on instance variable
instanceVar.someMethod();
// Legal, scoped local variable
localVar : MyClass = new MyClass( 1 );
// Legal, method on scoped local variable
localVar.someMethod();
// Legal, static variable
staticVar = new MyClass ( 1 );
// Legal, method on static variable
staticVar.someMethod();
}
It makes sense if you think about it a little, but it's not an entirely clear concept at first.

Related

Actionscript : Variable not found from another class' function

I tried doing
trace(classname.functionname.variablename);
//or
trace(classname.functionname().variablename);
Didn't work.. any idea, to get from the classname.as the variable, that's inside a function?
Btw i tried making the function static, still didn't work
Any idea?
There's no way, as those variables that are defined inside a function only live as long as the function is executed, and disappear once there's a return or end of function body. In order to get whatever value you want from a function, make a class variable outside the function, assign it the value you want within that function, and address it from elsewhere.
class test {
public static var foo:Number;
function bar():void {
// ... some code
foo=baz*2.54;
// ... more code
}
}
class elsewhere {
...
trace(test.foo);
...
}
the variables created inside a function are only available in the scope of that function.
if the variables are class member variables (declared public on a class);
public class x {
public var varName:String="";
}
you will be able to access them as
classInstanceRef.varName
needless to say you will need to instantiate from that class an instance.
Unless your variable is declared static on the class
public static varName:String="";
and in that case you can access it using
className.varName;

ActionScript 3 Singleton instantiation - advice

I have an AS3 Singleton:
package
{
public class Singleton
{
public function Singleton(enforcer:SingletonEnforcer):void
{
if(!enforcer){throw new Error("Only one instance of Singleton Class allowed.");}
}
private static var _instance:Singleton;
public static function getInstance():Singleton
{
if(!Singleton._instance)
{
Singleton._instance=new Singleton(new SingletonEnforcer());
}
return Singleton._instance;
}
}
}
class SingletonEnforcer{}
Consider prop and func() to be a property and method respectively of the Singleton class.
How should I access them?
1. Make them static and use this:
Singleton.getInstance();
Singleton.prop;
Singleton.func();
2. Not make them static and use this:
Singleton.getInstance().prop;
Singleton.getInstance().func();
Does it matter, or is it just visual prefference?
Thank you.
The reason to use a singleton instance is so that you can have class members used in a (relatively) static way.
I won't get into the arguments over whether or not to use a singleton here, there's a very long debate over whether it's a good pattern or not.
Typically, when singletons are used, you store access to them in a local variable and use them like any other class instance. The primary difference, is instead of using:
foo = new Foo();
You use:
foo = Foo.instance;
//Actionscript supports properties which makes this a self-initializing call
-or-
foo = Foo.getInstance();
Followed by
foo.bar();
foo.baz();
foo.fizz = 'buzz';
This doesn't mean that Foo can't have static members of the class, but the rules for adding static members on a Singleton are the same for adding static members to any other class. If the function belongs to the instance, it should be used on the instance, if it belongs to the class, it should be static.

What values are safe to use to initialize class definition's static and const members?

Phrased differently, this question could read, "What is the order of compile-time variable declarations and definitions?"
I can't recall specific examples at the moment, but I know I've run into trouble when initializing const and static values in my class definitions due to the declaration of those values occurring out of order.
I know I can instantiate objects when declaring static const members, like so:
public class ConstsWithNewObjects {
public static const DEFINED_NOW_2:Object = {something:"Defined!"};
public static const DEFINED_NOW_3:Object = new CustomObject("Defined!");
}
But, if I'm accessing one of those members from another static or const value, I imagine race conditions arising, like so:
public class ConstsWithOtherConsts {
public static const DEFINED_NOW_1:Object = DEFINED_NOW_3; // Does this exist, yet?
}
ActoinScript Hero Jack Dunstan has covered this exact topic in great detail on his blog: Class Bootup Part 2.
Regardless of Jack's findings; I would recommend, for the sanity of your readers; that you keep your static initialiser code as clean, and simple as possible - don't forget that static fields can call static methods; you can also make use of a static Class initialiser method as well.

AS3 Get the current class name from a static method

i have to read the current class name inside a static method. For non-static method it's easy i just call getQualifiedClassName(this) but inside a static method this is off course invalid. Any idea ?
Thanks
You can use getQualifiedClassName(prototype.constructor)
in the class' static method
You don't have a direct way of doing this. If is just inside one class that you need this, you can try to add a static member holding a reference to the class.
static private const CLASS:Object = YourReflectedClass;
then, just use that in your static method:
protected static function doReflection(): void {
var className:String = getQualifiedClassName(CLASS);
}
It would be helpful to know more about the use and the setup.

Should a class ever have static and non-static members

I'm trying to figure out when it would be appropriate for a class to have both static and non-static functions. AKA:
$obj = new ClassA;
$obj->doOOPStuff();
$something = ClassA::doStaticStuff();
Note: This example is done in PHP, however the question is language agnostic .
It seems that if you have a class that is meant to be instantiated, any functions that can be called statically, most likely belong in another class.
Is there any viable cases where I would have a class that used static AND non-static members?
One example: when Creation has to happen in a specific way.
class Foo {
public:
static Foo* Create(...params...);
private:
Foo();
};
Consider String class in .NET. It contains a non-static Split method which breaks some instance into a string[] and a static Join method, which takes a string[] and transform it into a string again.
A static method is applicable when you don't need to keep any state. So Math.Sin() just depends on its parameters and, given same parameters, output will always be the same. A non-static method can have different behavior is called multiple times, as it can keep a internal state.
If the functionality provided by static methods is relevant to that class and its objects, why not. It is pretty common.
Static method are most often factory methods
public class MyClass {
public static MyClass createMyClass(int a, double b) {..}
public static MyClass createSubclassOfMyClass(int c, boolean cond) {..}
public int calculateThis();
public double calculateThat();
}
Another use is to access some property that is logically bound that that class, but not separately to instances. For example - a cache:
(Note - of course synchronization should be taken into account in this example)
public class MyClass {
public static final Cache cache = new Cache();
public static void putInCacheIfNeeded(Object obj) {..}
public static void replaceInCache(Object obj) {..}
public void doSomethingCacheDependend(Object obj) {
if (something) {
MyClass.putInCacheIfNeeded(obj);
} else {
MyClass.replaceInCache(obj);
}
}
}
(Java language for the examples)
Imagine your constructor has two overloads that both are strings:
public class XmlDocument
{
public static XmlDocument CreateFromFile(string filePath);
public static XmlDocument CreateFromXml(string xml);
}
The static function can provide meaningful name to the constructor.
$dialog = DialogFoo::createOpenDialog();
$dialog = DialogFoo::createDocumentOpenDialog();
$dialog = DialogFoo::createImageOpenDialog();
It could also be used to enforce Singleton pattern.
$dialog = DialogFoo::getInstance()
Static class members are most useful where everything must either be in an object or be in a global scope; they are less useful in a language such as Python that supports module-level scopes.
I use static methods to instantiate new objects when I dont want the to give access to the constructor. I ensure that any necessary preconditions are carried out on the class before creating and object. In this example I have a counter to return how many objects are created, if I have 10 objects I prevent any more from being instantiated.
class foo {
private:
static int count;
foo() {}
public:
static foo bar() {
count++;
if (count<=10){
return new foo;
} else {
return null;
}
Let's assume a class has instance methods, here are some good use case for having static methods too:
For static utility methods
Such methods apply to any instance, for example String.format(String, Object...) in Java.
Use them when you don't want to create a specific instance for the job.
For static factory methods
Factory methods are methods that simply instantiate objects like the getInstance() and valueOf() methods in the Java API. getInstance() is the conventional instantiation method in singletons while valueOf() are often type-conversion methods, like in String.valueOf(int).
Use them to improve performance via object-caching, in interface-based frameworks (like the Collections Framework in Java) where you may want to return a subtype, to implement singletons (cough).
In general, static functions produce functionality highly related to class itself. It may be some helper functions, factory methods etc. In this case all functionality contains in one place, it correspond to DRY principle, increases cohesion and reduces coupling.