Immutable Collections Actionscript 3 - 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).

Related

How do I bind to an existing item in an NSCollectionViewItem?

An NSCollectionViewItem is derived from NSViewController. I use it as a prototype in an NSCollectionView. It has a property called RepresentedObject. Normally, I would use something like
var set = this.CreateBindingSet<DevViewController, DevViewModel> ();
set.Bind (devTextField).To (vm => vm.Text);
set.Bind (devTextView).To (vm => vm.BigText);
to bind UI elements with the vm. In the case of the NSCollectionViewItem, I want to bind to properties in the RepresentedObject. How do I do this?
NSCollectionView.Content takes NSObject[]. I'm currently taking my List and making an NSObject[] where each item in there is NSObject.FromObject(myClass) - which itself may not be the right approach.
Thanks in advance!
Update. It seems that if I can make my NSObject a KVO'd object ala http://cocoa-mono.org/archives/153/kvc-kvo-and-cocoa-bindings-oh-my-part-1/ that the bindings would automatically work.
The general approach of MvvmCross and its binding layer is that:
it tries to work with native controls,
but it also tries to encourage you to keep your ViewModel objects independent and unaware of any native choices.
So if you're trying to use a native control which requires you to supply a NSObject[] array, and you want to display (say) a list of customers, then a reasonable design choice within MvvmCross would be:
within the ViewModel:
to use a Customer object which provides INotifyPropertyChanged
to supply a List<Customer> as a parameter on your ViewModel
within the View:
to supply a NSObject[]
somewhere between the two
find:
a way of mapping your List<> to an []
and find a way of mapping your Customer to an NSObject
this can be found either:
using inheritance of the View and providing a custom C# property for binding
or using a custom binding
or using a value converter
The challenge of mapping the Customer to an NSObject is a particularly interesting one. If your end view is looking for KVO type functionality then I believe the conversion can be done by using a small Converter class which maps ValueForKey/SetValueForKey to their .Net reflection equivalent, and which maps INotifyPropertyChanged events to their DidChangeValue NSObject equivalent. I've not personally done this... but it feels like it should be doable, and (with a little caching of PropertyInfo objects) it should probably be reasonably efficient too.
Some final notes:
if you are marshalling a lot of calls between KVO and .Net reflection and this does impact your application's performance, then you may find using Rio style Field binding might be a faster experience, or you may find that it's faster to write hard-coded non-reflection based wrappers for your specific types.
if your ViewModel collection is mutable - e.g. it supports INotifyCollectionChanged then there may also be other interesting and reasonably efficient ways you can respond to the collection change events - although your view may not support these particularly 'beautifully' without some additional animation work.

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.

Should we avoid to use Object as the input parameter/ output value of a method?

Take Java syntax as an example, though the question itself is language independent. If the following snippet takes an object MyAbstractEmailTemplate as input argument in the method setTemplate, the class MyGateway will then become tightly-coupled with the object MyAbstractEmailTemplate, which lessens the re-usability of the class MyGateway.
A compromise is to use dependency-injection to ease the instantiation of MyAbstractEmailTemplate. This might solve the coupling problem
to some extent, but the interface is still rigid, hardly providing enough flexibility to
other developers/ applications.
So if we only use primitive data type (or even plain XML in web service) as the input/ output of a method, it seems the coupling problem no longer exists. So what do you think?
public class MyGateway {
protected MyAbstractEmailTemplate template;
public void setTemplate(MyAbstractEmailTemplate template) {
this.template = template;
}
}
It's pretty difficult to understand what you are really asking, but going the route of typing everything to Object does not lead to loose coupling because you can't do anything with the input without downcasting, which would break the Liskov Substituion Principle.
Taken to the extreme it leads you here:
public class MyClass
{
public object Invoke(object obj);
}
This is not loose coupling, it's just obscure and hard-to-maintain code.
The name MyAbstractEmailTemplate makes me believe that you are talking about an abstract class.
You should always program against interfaces, so instead of having MyGateway depend on MyAbstractEmailTemplate, it should depend on an EmailTemplate interface, where MyAbstractEmailTemplate implements EmailTemplate. Then, you can pass your custom implementations around as you want to, without further tight coupling.
Combine this with DI and you've got yourself a pretty decent solution.
Not exactly sure what you mean with "the interface is still rigid", but obviously you should design your interface in such a way that it provides the functionality you need.
MyGateway has to assume something about the inputs. Even if it used XML, it would have to assume something about the structure and content of the XML. Coupling isn't an evil in its own right; expresses the contract between two pieces of code. The oft-repeated advice to avoid tight coupling is really just saying that coupling should express the essence of a contract, not more and not less. Passing a specific type (particularly an interface type) is a very good way to achieve this balance.
The first problem you will run into is that a lot of types are simply not representable by a primitive data type (It's a Java problem that there are primitive types at all.).
The coupling should be reduced by using a proper inheritance hierarchy. What means proper? The method should take exactly that part of the interface as a parameter that is need. Not more not less.
After all you won't be able to avoid dependencies. Methods have to know about what they can do with their input or have to able to make assumptions (see C++ concepts) about the capabilities of the input.
IMHO there is nothing inherently wrong in using objects (wth small cap, not Objects) as method parameters and/or class members. Yes, these create dependencies. You can manage this in (at least) two ways:
acknowledge that by creating this dependency, the two classes become tightly coupled. This is entirely appropriate in many cases, where two (or more) classes in fact form a component, which is a meaningful unit of reuse in itself, and its parts may not make much sense or be interchangeable.
if there are multiple interchangeable candidates for a method parameter, these are obvious candidates to form a class hierarchy. Then you program for the interface and can pass any object of any class implementing that interface as parameter to your method. Note that the phrase "there are multiple interchangeable candidates for a method parameter" is a loose rephrasing of the Liskov Substitution Principle, which is the foundation of polymorphism.
in some languages, e.g. C++, the third way would be using templates. Then you need no common interface, only specific methods/members need to resolvable when the template is instantiated. However, since instantiation happens at compile time, this is entirely static binding.
sThe problem is I would say, that the best java can offer are interfaces and people start to see that they are too rigid. It would be interesting to use something like what is in Go language, that allows flexible checking for all methods of an interface to be present in the type, you do not have to be explicit about implementing some interface. We also need something better than interfaces to specify the constraints - maybe some sort of contracts. Another thing is the interface evolution.

Can I change class types in a setter with an object-oriented language?

Here is the problem statement: Calling a setter on the object should result in the object to change to an object of a different class, which language can support this?
Ex. I have a class called "Man" (Parent Class), and two children namely "Toddler" and "Old Man", they are its children because they override a behaviour in Man called as walk. ( i.e Toddler sometimes walks using both his hands and legs kneeled down and the Old man uses a stick to support himself).
The Man class has a attribute called age, I have a setter on Man, say setAge(int ageValue). I have 3 objects, 2 toddlers, 1 old-Man. (The system is up and running, I guess when we say objects it is obvious). I will make this call, toddler.setAge(80), I expect the toddler to change to an object of type Old Man. Is this possible? Please suggest.
Thanks,
This sounds to me like the model is wrong. What you have is a Person whose relative temporal grouping and some specific behavior changes with age.
Perhaps you need a method named getAgeGroup() which returns an appropriate Enum, depending on what the current age is. You also need an internal state object which encapsulates the state-specific behavior to which your Person delegates behavior which changes with age.
That said, changing the type of an instantiated object dynamically will likely only be doable only with dynamically typed languages; certainly it's not doable in Java, and probably not doable in C# and most other statically typed languages.
This is a common problem that you can solve using combination of OO modelling and design patterns.
You will model the class the way you have where Toddler and OldMan inherit from Man base class. You will need to introduce a Proxy (see GoF design pattern) class as your access to your Man class. Internally, proxy hold a man object/pointer/reference to either Toddler or OldMan. The proxy will expose all the interfaces that is exposed by Man class so that you can use it as it is and in your scenario, you will implement setAge similar to the pseudo code below:
public void setAge(int age)
{
if( age > TODDLER_MAX && myMan is Toddler)
myMan = new OldMan();
else
.....
myMan.setAge(age);
}
If your language does not support changing the classtype at runtime, take a look at the decorator and strategy patterns.
Objects in Python can change their class by setting the __class__ attribute. Otherwise, use the Strategy pattern.
I wonder if subclassing is really the best solution here. A property (enum, probably) that has different types of people as its possible values is one alternative. Or, for that matter, a derived property or method that tells you the type of person based on the age.
Javascript can do this. At any time you can take an existing object and add new methods to it, or change its existing methods. This can be done at the individual object level.
Douglas Crockford writes about this in Classical Inheritance in JavaScript:
Class Augmentation
JavaScript's dynamism allows us to add
or replace methods of an existing
class. We can call the method method
at any time, and all present and
future instances of the class will
have that method. We can literally
extend a class at any time.
Inheritance works retroactively. We
call this Class Augmentation to avoid
confusion with Java's extends, which
means something else.
Object Augmentation
In the static object-oriented
languages, if you want an object which
is slightly different than another
object, you need to define a new
class. In JavaScript, you can add
methods to individual objects without
the need for additional classes. This
has enormous power because you can
write far fewer classes and the
classes you do write can be much
simpler. Recall that JavaScript
objects are like hashtables. You
can add new values at any time. If the
value is a function, then it becomes a
method.
Common Lisp can: use the generic function CHANGE-CLASS.
I am surprised no one so far seemed to notice that this is the exact case for the State design pattern (although #Fadrian in fact described the core idea of the pattern quite precisely - without mentioning its name).
The state pattern is a behavioral software design pattern, also known as
the objects for states pattern. This pattern is used in computer
programming to represent the state of an object. This is a clean way for an
object to partially change its type at runtime.
The referenced page gives examples in Java and Python. Obviously it can be implemented in other strongly typed languages as well. (OTOH weakly typed languages have no need for State, as these support such behaviour out of the box.)

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.