Instantiate class on variable declaration or within constructor [duplicate] - actionscript-3

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Where is the “proper” place to initialize class variables in AS3
I was wondering if anyone knows wether its better to instantiate class on it's variable declaration or within a constructor? For example, this:
protected var _errorHandler:ErrorHandler = new ErrorHandler();
or this:
protected var _errorHandler:ErrorHandler;
public function someClass() {
_errorHandler = new ErrorHandler();
}
A small point I think, but I want my code to robust and efficient as possible!
Thanks
Chris

Initialization in the constructor is preferred, for readability--for being able to easily see what gets initialized when. The least readable option would be to mix these, which I can't recommend.
There is a third option that you will see AS3 programmers use:
No initialization in the variable declarations
Empty (or nearly empty) constructor
All initialization done in one or more dedicated init() functions
This approach has two things to offer:
You can easily reset the object for re-use by calling init again
You can get around the limitation that AS3 does not let you overload the constructor like other similar languages (Java/C++/C#). You might want to, for example, be able to initialize a data structure with one or more different types of objects.
As far as performance goes, I believe your two examples would compile down to the same byte code. The AS3 compiler makes a special class initializer for static declarations that are outside the constructor, but for regular member variables initialized at declaration time, I expect it just moves the initializations to inside the constructor for you. But does it move them ahead or after what is explicitly in the contructor? I don't remember, which is why I cite readability as a main reason to put everything in the constructor yourself :-)

Related

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.

When to make a method static? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I'd like to know how people decide whether to define a method as static. I'm aware that a method can only be defined as static if it doesn't require access to instance fields. So let's say we have a method that does not access instance fields, do you always define such a method as static, or only if you need to call it statically (without a reference to an instance).
Perhaps another way of asking the same question is whether you use static or non-static as the default?
I use static methods whenever I can. Advantages:
When calling a static method from inside an instance method, you can be sure that there are no side-effects on the state of the current object.
From inside a static method, you can be sure you don't accidentally modify any state of the object instance.
You can use a static method from outside the class without constructing an instance. If it was possible to make the method static, it clearly doesn't need an instance, so there's no need to require one.
Static methods may be slightly more efficient because no "this" pointer needs to be passed, and no dynamic dispatch is necessary.
Kevin Bourrillion wrote an insightful answer on this topic some time ago (admittedly from a Java perspective, but I think it's applicable to other languages too).
He argues that you should basically only use static methods for pure functions.
A "pure function" is any method which does not modify any state and whose
result depends on nothing but the
parameters provided to it. So, for
example, any function that performs
I/O (directly or indirectly) is not a
pure function, but Math.sqrt(), of
course, is.
I tend to agree. (Although in my own code, traditionally, I've probably used way too many static helper methods all over the place... :-P And this surely has made code that uses those methods harder to test.)
If what the method does depend solely on its arguments, you can make it static. If the method does not instantiate any other of your user defined classes, you can make it static. The default, though, is to have it as non-static.
Use static methods when you are performing operations that do not operate on instances of the class.
A perfect example would be a sqrt method of a Math class.
It depends. In languages where non-member functions are possible I'd say that most of the time, if the method could be made static, it should be made a non-member function instead, non-friend if possible. You can tell I have a mostly C++ background.
In "pure" OO languages where non-member functions are not possible it would depend on whether the method is only "incidentally" static (i.e. it just happens not to need access to instance members), or is truly logically static - it is a method of the whole class instead of for a particular instance.
Non static by default, static when I need the functionality to be available from at least two different classes, and I don't want to waste a constructor.
ps. Archimedes rules!
(C#) By default, I use static methods in static classes and non-static methods in non-static classes.
As I elaborate a class, I find myself naturally converging on making it entirely static or entirely non-static. Practially speaking, if I start wanting to define static members within a non-static class, I often find that it will eventually make the most sense to break those out into a separate static class -- either a utility class like Math or a global application class (like .NET's ConfigurationManager).
From an object-oriented perspective, a method is doing something to/with an object. So if you're using an instantiated object, it makes the most sense to me to think of that object's methods as non-static. Technically, you technically can make a non-static class have static members if they don't require access to an instance. But ostensibly, at least, a class's methods would still be doing something to/with that class, so I would still make them non-static. All things being equal, that is.
in context of python -
staticmethod are basically a normal function, we keep in the class only because of some logical reasons. classmethod takes 'class' as a first argument, default method takes instance aka self as a first argument but staticmethod does not takes any any argument.

To init or to construct

I'm reviewing some code and I'm seeing a lot of this:
class Foo
{
public:
Foo()
{
// 'nuffin
}
void init()
{
// actual construction code
}
} ;
The only advantage I can see is if you create a Foo without using a pointer and you want to hold off its construction code until later, then you can.
Is this a good idea or a bad idea?
I dislike it. It seems to me that after construction, an object should be... well... constructed. That code leaves it in an invalid state instead, which is almost1 never a good thing.
1 Weasel word inserted to account for unforeseen circumstances.
In general, I agree that it's something to be avoided. But something none of the answers so far have addressed is the possibility that initialization may fail. Constructors cannot fail, so if your constructor allocates memory, or opens a file, or does anything else that may fail, you need a way to tell the caller that an error occurred. If you do the initialization in the constructor, then you need to have a flag that indicates whether or not the initialization succeeded, and then ensure that the caller checks that flag.
If you have a separate init() routine that must be called before anything else works, callers are more likely to check that return code than to call a didInitializationSucceed() method after creating the object.
Two-stage construction is generally considered a bad idea, if there are methods on the class which rely on the object being in some initialised state. Generally, I prefer constructors which guarantee the object is in a good state, or if that cannot be done (perhaps because some of the arguments to the constructor were invalid), throw an exception, so there is never an instances of your class which is in a bad state.
Requiring consumers of your object to remember to call init() is a bad idea, because they won't.
One case where this may apply is when 'Foo' is a attribute of another class and cannot be fully constructed before the parent-class is done. Only then can 'Foo' be 'filled-in'.
I believe constructor should basically do the init() part as well. Unless the object is fully constructed, it shouldn't be used.
Also, initializing in constructor allows you to make use of RAII. The basic point of RAII is to represent a resource by a local object, initialize in constructor, so that the local object's destructor will release the resource. That way, the programmer cannot forget to release the resource.
In some languages (read: C++) you can't call a constructor from another constructor, so if you want a common part of several constructors you need to put it in a separate method, and I've seen the name init() used for that. But that is not what you're talking about?
I use the contructor and init if I am instantiating objects that are based on a database call. So, if I need an empty object so that I can populate it and then save it to the database, I construct with no parameters and don't call init(). Whereas if I need to retrieve the object members from the db, I'll contruct($param) and pass the $param to init($param).
Generally, source code should be as simple as possible, and your example is presented without the context, so it's just more complicated than necessary and therefore your example is a bad idea.
However, there may be some semantic contexts, where it may make sense to be able to deliver uninitialized objects - for instance, if the context requires a container to have objects but you don't want to initialize them until later because initialization is slow and/or maybe the objects are not needed. In those cases, the additional complexity may make something else simpler.
Although it cannot be considered a normal or preferred way of constructing objects, under some circumstances that maybe a way to go. For example you may need to construct an object just to indicate its existence (in some list, where count does matter etc.), but to init it later only if this particular object is used for the first time as initializing whole collection of objects would take to much time.
In that case it's good to expose the fact that object may be not initialized by including a method like isInitialized(). Also that way you can transfer initialization to another thread in order not to block the main thread of the application.
The difference is that initialization happens after the call to the super class's constructor but before any code is executed in your local class constructor. Therefore, it really depends on your needs.

Immutable Collections Actionscript 3

I've been trying lately to implement some clean coding practices in AS3. One of these has been to not give away references to Arrays from a containing object. The point being that I control addition and removal from one Class and all other users of the Array receive read only version.
At the moment that read only version is a ArrayIterator class I wrote, which implements a typical Iterator interface (hasNext, getNext). It also extends Proxy so it can be used in for each loops just as a Array can.
So my question is should this not be a fundamental feature of many languages? The ability to pass around references to read only views of collections?
Also now that there is improved type safety for collections in AS3 , in the form of the Vector class, when I wrap a a Vector in a VectorIterator I lose typing for the sake of immutability. Is there a way to implement the two desires, immutability and typing in AS3?
It seems that using an Iterator pattern is the best way currently in AS3 to pass a collection around a system, while guaranteeing that it will not be modified.
The IIterator interface I use is modeled on the Java Iterator, but I do not implement the remove() method, as this is considered a design mistake by many in the Java community, due to it allowing the user to remove array elements. Below is my IIterator implemention:
public interface IIterator
{
function get hasNext():Boolean
function next():*
}
This is then implemented by classes such as ArrayIterator, VectorIterator etc.
For convenience I also extend Proxy on my concrete Iterator classes, and provide support for the for-each loops in AS3 by overriding the nextNameIndex() and nextValue() methods. This means code that typically used Arrays does not need to change when using my IIterator.
var array:Array = ["one", "two", "three"]
for each (var eachNumber:String in array)
{
trace(eachNumber)
}
var iterator:IIterator = new ArrayIterator(array)
for each (var eachNumber:String in iterator)
{
trace(eachNumber)
}
Only problem is... there is no way for the user to look at the IIterator interface and know that they can use a for-each loop to iterate over the collection. They would have to look at the implementation of ArrayIterator to see this.
Some would argue that the fact that you can implement such patterns as libraries is an argument against adding features to the language itself (for example, the C++ language designers typically say that).
Do you have the immutability you want via the proxy object or not? Note, you can have the VectorIterator constructor take a mandatory Class parameter. Admittedly this is not designer friendly at the moment, but lets hope things will improve in the future.
I have created a small library of immutable collection classes for AS3, including a typed ordered list, which sounds like it would meet your needs. See this blog post for details.
Something I do to achieve this is to have the class that maintains the list only return a copy of that list in a getter via slice(). As an example, my game engine has a class Scene which maintains a list of all the Beings that have been added to it. That list is then exposed as a copy like so:
public function get beings():Vector.<Being>
{
return _beings.slice();
}
(Sorry to revive an old thread, I came across this while looking for ways to implement exactly what Brian's answer covers and thought I would throw my 2 cents in on the matter).

How should I refactor my code to remove unnecessary singletons?

I was confused when I first started to see anti-singleton commentary. I have used the singleton pattern in some recent projects, and it was working out beautifully. So much so, in fact, that I have used it many, many times.
Now, after running into some problems, reading this SO question, and especially this blog post, I understand the evil that I have brought into the world.
So: How do I go about removing singletons from existing code?
For example:
In a retail store management program, I used the MVC pattern. My Model objects describe the store, the user interface is the View, and I have a set of Controllers that act as liason between the two. Great. Except that I made the Store into a singleton (since the application only ever manages one store at a time), and I also made most of my Controller classes into singletons (one mainWindow, one menuBar, one productEditor...). Now, most of my Controller classes get access the other singletons like this:
Store managedStore = Store::getInstance();
managedStore.doSomething();
managedStore.doSomethingElse();
//etc.
Should I instead:
Create one instance of each object and pass references to every object that needs access to them?
Use globals?
Something else?
Globals would still be bad, but at least they wouldn't be pretending.
I see #1 quickly leading to horribly inflated constructor calls:
someVar = SomeControllerClass(managedStore, menuBar, editor, sasquatch, ...)
Has anyone else been through this yet? What is the OO way to give many individual classes acces to a common variable without it being a global or a singleton?
Dependency Injection is your friend.
Take a look at these posts on the excellent Google Testing Blog:
Singletons are pathologic liars (but you probably already understand this if you are asking this question)
A talk on Dependency Injection
Guide to Writing Testable Code
Hopefully someone has made a DI framework/container for the C++ world? Looks like Google has released a C++ Testing Framework and a C++ Mocking Framework, which might help you out.
It's not the Singleton-ness that is the problem. It's fine to have an object that there will only ever be one instance of. The problem is the global access. Your classes that use Store should receive a Store instance in the constructor (or have a Store property / data member that can be set) and they can all receive the same instance. Store can even keep logic within it to ensure that only one instance is ever created.
My way to avoid singletons derives from the idea that "application global" doesn't mean "VM global" (i.e. static). Therefore I introduce a ApplicationContext class which holds much former static singleton information that should be application global, like the configuration store. This context is passed into all structures. If you use any IOC container or service manager, you can use this to get access to the context.
There's nothing wrong with using a global or a singleton in your program. Don't let anyone get dogmatic on you about that kind of crap. Rules and patterns are nice rules of thumb. But in the end it's your project and you should make your own judgments about how to handle situations involving global data.
Unrestrained use of globals is bad news. But as long as you are diligent, they aren't going to kill your project. Some objects in a system deserve to be singleton. The standard input and outputs. Your log system. In a game, your graphics, sound, and input subsystems, as well as the database of game entities. In a GUI, your window and major panel components. Your configuration data, your plugin manager, your web server data. All these things are more or less inherently global to your application. I think your Store class would pass for it as well.
It's clear what the cost of using globals is. Any part of your application could be modifying it. Tracking down bugs is hard when every line of code is a suspect in the investigation.
But what about the cost of NOT using globals? Like everything else in programming, it's a trade off. If you avoid using globals, you end up having to pass those stateful objects as function parameters. Alternatively, you can pass them to a constructor and save them as a member variable. When you have multiple such objects, the situation worsens. You are now threading your state. In some cases, this isn't a problem. If you know only two or three functions need to handle that stateful Store object, it's the better solution.
But in practice, that's not always the case. If every part of your app touches your Store, you will be threading it to a dozen functions. On top of that, some of those functions may have complicated business logic. When you break that business logic up with helper functions, you have to -- thread your state some more! Say for instance you realize that a deeply nested function needs some configuration data from the Store object. Suddenly, you have to edit 3 or 4 function declarations to include that store parameter. Then you have to go back and add the store as an actual parameter to everywhere one of those functions is called. It may be that the only use a function has for a Store is to pass it to some subfunction that needs it.
Patterns are just rules of thumb. Do you always use your turn signals before making a lane change in your car? If you're the average person, you'll usually follow the rule, but if you are driving at 4am on an empty high way, who gives a crap, right? Sometimes it'll bite you in the butt, but that's a managed risk.
Regarding your inflated constructor call problem, you could introduce parameter classes or factory methods to leverage this problem for you.
A parameter class moves some of the parameter data to it's own class, e.g. like this:
var parameterClass1 = new MenuParameter(menuBar, editor);
var parameterClass2 = new StuffParameters(sasquatch, ...);
var ctrl = new MyControllerClass(managedStore, parameterClass1, parameterClass2);
It sort of just moves the problem elsewhere though. You might want to housekeep your constructor instead. Only keep parameters that are important when constructing/initiating the class in question and do the rest with getter/setter methods (or properties if you're doing .NET).
A factory method is a method that creates all instances you need of a class and have the benefit of encapsulating creation of the said objects. They are also quite easy to refactor towards from Singleton, because they're similar to getInstance methods that you see in Singleton patterns. Say we have the following non-threadsafe simple singleton example:
// The Rather Unfortunate Singleton Class
public class SingletonStore {
private static SingletonStore _singleton
= new MyUnfortunateSingleton();
private SingletonStore() {
// Do some privatised constructing in here...
}
public static SingletonStore getInstance() {
return _singleton;
}
// Some methods and stuff to be down here
}
// Usage:
// var singleInstanceOfStore = SingletonStore.getInstance();
It is easy to refactor this towards a factory method. The solution is to remove the static reference:
public class StoreWithFactory {
public StoreWithFactory() {
// If the constructor is private or public doesn't matter
// unless you do TDD, in which you need to have a public
// constructor to create the object so you can test it.
}
// The method returning an instance of Singleton is now a
// factory method.
public static StoreWithFactory getInstance() {
return new StoreWithFactory();
}
}
// Usage:
// var myStore = StoreWithFactory.getInstance();
Usage is still the same, but you're not bogged down with having a single instance. Naturally you would move this factory method to it's own class as the Store class shouldn't concern itself with creation of itself (and coincidentally follow the Single Responsibility Principle as an effect of moving the factory method out).
From here you have many choices, but I'll leave that as an exercise for yourself. It is easy to over-engineer (or overheat) on patterns here. My tip is to only apply a pattern when there is a need for it.
Okay, first of all, the "singletons are always evil" notion is wrong. You use a Singleton whenever you have a resource which won't or can't ever be duplicated. No problem.
That said, in your example, there's an obvious degree of freedom in the application: someone could come along and say "but I want two stores."
There are several solutions. The one that occurs first of all is to build a factory class; when you ask for a Store, it gives you one named with some universal name (eg, a URI.) Inside that store, you need to be sure that multiple copies don't step on one another, via critical regions or some method of ensuring atomicity of transactions.
Miško Hevery has a nice article series on testability, among other things the singleton, where he isn't only talking about the problems, but also how you might solve it (see 'Fixing the flaw').
I like to encourage the use of singletons where necessary while discouraging the use of the Singleton pattern. Note the difference in the case of the word. The singleton (lower case) is used wherever you only need one instance of something. It is created at the start of your program and is passed to the constructor of the classes that need it.
class Log
{
void logmessage(...)
{ // do some stuff
}
};
int main()
{
Log log;
// do some more stuff
}
class Database
{
Log &_log;
Database(Log &log) : _log(log) {}
void Open(...)
{
_log.logmessage(whatever);
}
};
Using a singleton gives all of the capabilities of the Singleton anti-pattern but it makes your code more easily extensible, and it makes it testable (in the sense of the word defined in the Google testing blog). For example, we may decide that we need the ability to log to a web-service at some times as well, using the singleton we can easily do that without significant changes to the code.
By comparison, the Singleton pattern is another name for a global variable. It is never used in production code.