Map/Dictionary which limit entries size in ActionScript 3 - actionscript-3

In Java, this can be done with LinkedHashMap by removing eldest entry/oldest accessed entry. Any equivalent class in ActionScript 3?
Thanks.

No, unfortunately not. You could easily implement one, if I were going to implement it I would extend the Proxy object It'll give you a fair bit of flexibility.
UPDATE:
This update is to clarify on the question in the comment by the OP. Comment was "It will be a new class extends Proxy and not Dictionary/etc?"
Yes, you would want to extend Proxy, the reason for this is that it allows you to override several magic methods to accomplish your goal. Particularly in your case, you can override setProperty(name:*, value:*):void. This method will be called every time a property is set on your class (its up to you to supply the set implementation) so you can count the number of values that are set at a given time. If you extend Object or dictionary, you do not have access to this, and have know way of knowing when a new property is set.
If you extended object instead, you would need to rely on an interface to to acheive your goal, requiring user to set properties through method calls.
A Proxy implementation would allow you still set properties like this:
myObj.foo = 'bar';
myObj["foo"] = 'bar';
A method implementation (extending Object) would look like this:
myObject.setVal("name", "val");

Related

Multiple logics (N number of clients) handled with only one function. All call the same function, HOW TO? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a corporate application written in python/Django (no python experience required to answer this). Its SAAS basically.
Few of the clients seems to have different requirement for a few modules.
Lets say there is a URL
www.xyz.com/groups
which is used by all clients but a few of the clients want to have different output on call of the same URL.
I want to know how can i do that without writing new function for each client or writing conditions in a single function.
Its a silly question i know but there must be some solution to it, i know.
If your code is required to do "A" for case "a" and "B" for case "b" and "C" for case "c", then regardless of what solution you pick, somewhere in the code has to exists something that decides whever or not case 'a/b/c' occurs, and something must exist that will dispatch correct 'A/B/C' action for that case, and of course those A/B/C actions have to be written somewhere in the code, too.
Step outside of the code and think about it. If it is specified and must happen - it has to be coded somewhere. You cannot escape that. Now, if the cases/actions are trivial and typical, you might find some more-or-even-more configurable library that accidentally allows you to configure such cases and actions, and off you go, you have it "with no code" and no "clutter". But looking formally, the code is deep there in the library. So, the decider, dispatcher and actions are coded. Just not by you - by someone that guessed your needs.
But if your needs are nontrivial and highly specific, for example, if it require your various conditions to decide which a/b/c case is it - then most probably you will have to code the 'decider' part for yourself. That means lots of tree-of-IFs, nested-switches, rules-n-loops, or whatever you like or feel adequate. After this, you are left with dispatch/execute phase, and this can be realized in a multitude of ways - i.e. strategy pattern - it is exactly it: dispatch (by concrete class related to case) and execute (the concrete strategy has the concrete code for the case).
Let's try something-like-OO approach:
For example, if you have cases a/b/c for UserTypes U1,U2,U3, you could introduce three classes:
UserType1 inherits from abstract UserType or implements "DoAThing" interface
UserType2 inherits from abstract UserType or implements "DoAThing" interface
UserType3 inherits from abstract UserType or implements "DoAThing" interface
UserType1 implements virtual method 'doTheThing' that executes actionA
UserType2 implements virtual method 'doTheThing' that executes actionB
UserType3 implements virtual method 'doTheThing' that executes actionC
your Users stop keeping "UserType" of type "int" equal to '1/2/3' - now their type is an object: UserType1, UserType2 or UserType3
whenever you must do the thing for a given user, you now just:
result = user.getType().doTheThing( ..params..)
So, instead of iffing/switching, you use OO: tell, don't ask rule. If the action-to-do is dependent solely on UserType, then let the UserType perform it. The resulting code is as short as possible - but at the cost of number of classes to create and, well, ...
... the decider, dispatcher and actions are still in the code. Actions - obvious - in the various usertype clasess. Dispatch - obvious - virtual call by common abstract base method. And decider..? Well: someone at some point had to choose and construct the correct UserType object for the user. If user was stored in the database, if "usertype" is just an integer 1/2/3, then somewhere in your ORM layer those 1/2/3 numbers had to be decoded and translated into UserType1/2/3 classes/objects. That means, that you'd need there a tree-of-ifs or a switch or etc. Or, if you have an ORM smart enough - you just set up a bunch of rules and it did it for you, but that's just again delegating part of the job to more-or-even-more configurable library. Not mentioning that your UserType1/2/3 classes in fact became somewhat .. strategies.
Ok, let's attack the 'choose' part.
You can build a tree of ifs or switches somewhere to decide and assign, but imperative seems to smell. Or, with OO, you can try to polymorphize something so that "it will just do the right thing", but it will not solve anything since again you will have to choose the object type somewhere. So, let's try data-driven: let's use lookups.
we've got five implementations of an action
create a hash/dictionary/map
add usertype1->caseA to the map
add usertype2->caseC to the map
add usertype3->caseB to the map
add usertype4->caseA to the map
add usertype5->caseE to the map
....
now, whenever you have a user and need to decide, just look it up. Instead of a "case" you may hold a ready to use object of a strategy. Or a callable method. Or a typename. Or whatever you need. The point is that instead of writing
if( user.type == 1) { ... }
else if( user.type == 2) ...
or switching, you just look it up:
thing = map[ user.type ]
if ( thing is null ) ???
but, mind that without some care, you might sometimes NOT find a match in the map. And also, the map must be PREDEFINED for ALL CASES. So, simple if X < 100 may turn up into a hundred of entries 0..99 inside the map.
Of course, instead of a map, you may use some rule-engine and you could define a mapping like
X<100 -> caseA
X>=100 -> caseB
and then 'run' the rules against your usertype and obtain a 'result' that will tell you "caseA".
And so on.
Each of the parts - decide, dispatch, execute - you may implement in various ways, shorter or longer, more or less extensible, more or less configurable, as OO/imperative/datadriven/functional/etc - but you cannot escape them:
you have to define the discriminant of the cases
you have to define the implementation of the actions
you have to define the mapping case-to-action
How to do them, is a matter of your aesthetics, language features, frameworks, libraries and .. time you want to spend on creating and mantaining it.

Naming conventions for methods which must be called in a specific order?

I have a class that requires some of its methods to be called in a specific order. If these methods are called out of order then the object will stop working correctly. There are a few asserts in the methods to ensure that the object is in a valid state. What naming conventions could I use to communicate to the next person to read the code that these methods need to be called in a specific order?
It would be possible to turn this into one huge method, but huge methods are a great way to create problems. (There are a 2 methods than can trigger this sequence so 1 huge method would also result in duplication.)
It would be possible to write comments that explain that the methods need to be called in order but comments are less useful then clearly named methods.
Any suggestions?
Is it possible to refactor so (at least some of) the state from the first function is passed as a paramter to the second function, then it's impossible to avoid?
Otherwise, if you have comments and asserts, you're doing quite well.
However, "It would be possible to turn this into one huge method" makes it sound like the outside code doesn't need to access the intermediate state in any way. If so, why not just make one public method, which calls several private methods successively? Something like:
FroblicateWeazel() {
// Need to be in this order:
FroblicateWeazel_Init();
FroblicateWeazel_PerformCals();
FroblicateWeazel_OutputCalcs();
FroblicateWeazel_Cleanup();
}
That's not perfect, but if the order is centralised to that one function, it's fairly easy to see what order they should come in.
Message digest and encryption/decryption routines often have an _init() method to set things up, an _update() to add new data, and a _final() to return final results and tear things back down again.

Differences between variable instantiation outside constructor and in

I have to decide whether to put a variable within a constructor or outside, but I keep getting the feeling that I am missing information, I have looked at other posts on stack overflow, but all mentioned it was a matter of preference, yet I found two difference that I feel might be important:
-If I decide to put the variables within a constructor, then I must have an object parameter for any function that wish to alter the variables, even if the code is internal to the class.
-Subclassing would cause the variables to not appear, something that causes problems when the class and any subclasses must have the variables in order to operate properly.
I may be wrong on all of these points, but at 4am, I would rather be told I am wrong than commit a mistake due to pride. If this has been answered somewhere else and I missed it, I am sorry, and if you could post the link, I would be grateful.
actions inside the constructor are interpreted, all others are precompiled so they work faster
Like www0z0k already said, the declarations outside the constructor are merly interpreted, so declaring them outside can be a performance bost under some circumstances.
-If I decide to put the variables within a constructor, then I must have an object parameter for any function that wish to alter the variables, even if the code is internal to the class.
This is correct.
-Subclassing would cause the variables to not appear, something that causes problems when the class and any subclasses must have the variables in order to operate properly.
You should think about what you want to archive. Most times you should rather choose a good software design then to think about performance. This subclassing problem that you mentioned can also protect some variables from being changed.
Greetings,
iuiz
-Subclassing would cause the variables to not appear, something that causes
problems when the class and any
subclasses must have the variables in
order to operate properly.
If I understood you correctly you're looking for protected fields (or properties).
-If I decide to put the variables within a constructor, then I must have
an object parameter for any function
that wish to alter the variables, even
if the code is internal to the class.
Sry, I don't get that...
#Performance: with all that said about interpreted constructors you could add a simple init(...) function within your constructor which does all you would do in the constructor - but without being interpreted.
public function ConstructorOfClass(arg1:int, arg2:*)
{
init(arg1, arg2);
}
private function init(arg1:int, arg2:*):void
{
// do whatever you want here
}

When subclassing in AS3, is a new constructor function necessary?

Basic OOP question...
I want to add a couple functions to the Array class so that my program will be amazing and make me rich and famous overnight.
So I create a new subclass NewArray which extends Array. Do I need to write a constructor method for NewArray? If I leave it blank will it just use the parent's (Array's) constructor method?
Thanks
Yes, if you leave it blank it'll use the super-class' default constructor, which in the case of an Array is actually a constructor with a default value set:
Array(numElements:int = 0)
So by default you'll be creating an array with zero elements, which I guess is probably what you want anyway.
And don't forget this note from the docs:
You can extend the Array class and override or add methods. However, you must specify the subclass as dynamic or you will lose the ability to store data in an array.
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/Array.html

What is the difference between a property and an instance variable?

I think I've been using these terms interchangably / wrongly!
Iain, this is basically a terminology question and is, despite the "language-agnostic" tag associated with this question, very language/environment related.
For design discussions sake, property and instance variable can be used interchangeably, since the idea is that a property is a data item describing an object.
When talking about a specific language these two can be different. For example, in C# a property is actually a function that returns an object, while an instance variable is a non-static member variable of a class.
Hershi is right about this being language specific. But to add to the trail of language specific answers:
In python, an instance variable is an attribute of an instance, (generally) something that is referred to in the instance's dictionary. This is analogous to members or instance variables in Java, except everything is public.
Properties are shortcuts to getter/setter methods that look just like an instance variable. Thus, in the following class definition (modified from Guido's new style object manifesto):
class C(object):
def __init__(self):
self.y = 0
def getx(self):
if self.y < 0: return 0
else: return self.y
def setx(self, x):
self.y = x
x = property(getx, setx)
>>> z = C()
>>> z.x = -3
>>> print z.x
0
>>> print z.y
-3
>>> z.x = 5
>>> print z.x
5
>>> print z.y
5
y is an instance variable of z, x is a property. (In general, where a property is defined, there are some techniques used to obscure the associated instance variable so that other code doesn't directly access it.) The benefit of properties in python is that a designer doesn't have to go around pre-emptively encapsulating all instance variables, since future encapsulation by converting an instance variable to a property should not break any existing code (unless the code is taking advantage of loopholes your encapsulation is trying to fix, or relying on class inspection or some other meta-programming technique).
All this is a very long answer to say that at the design level, it's good to talk about properties. It is agnostic as to what type of encapsulation you may need to perform. I guess this principle isn't language agnostic, but does apply to languages beside python.
In objective c, a property is an instance variable which can take advantage of an overloaded dot operator to call its setter and getter. So my.food = "cheeseburger" is actually interpreted as [my setFood:"cheeseburger"]. This is another case where the definition is definitely not language agnostic because objective-c defines the #property keyword.
code example done in C#
public class ClassName
{
private string variable;
public string property
{
get{ return variable; }
set { variable = value; }
}
}
Maybe thats because you first came from C++ right?!
In my school days I had professors that said class properties or class atributes all the time. Since I moved to the Java C# world, I started hearing about members. Class members, instance members...
And then Properties apear! in Java and .NET. So I think its better for you to call it members. Wheather they are instance members (or as you called it instance variable) or class Members....
Cheers!
A property can, and I suppose mostly does, return an instance variable but it can do more. You could put logic in a property, aggregate values or update other instance variables etc. I think it is best to avoid doing so however. Logic should go into methods.
In Java we have something called JavaBeans Properties, but that is basically a instance variable that follows a certain naming pattern for its getter and setter.
At add to what has been said, in a langauge like C#, a property is essentially a get and set function. As a result, it can have custom logic that runs in addition to the getting/setting. An instance variable cannot do this.
A property is some sort of data associated with an object. For instance, a property of a circle is its diameter, and another is its area.
An instance variable is a piece of data that is stored within an object. It doesn't necessarily need to correspond directly with a property. For instance (heh), a circle may store its radius in an instance variable, and calculate its diameter and area based on that radius. All three are still properties, but only the radius is stored in an instance variable.
Some languages have the concept of "first class" properties. This means that to a client application, the property looks and is used like an instance variable. That is, instead of writing something like circle.getDiameter(), you would write circle.diameter, and instead of circle.setRadius(5), you would write circle.radius = 5.
In contrast to the other answers given, I do think that there is a useful distinction between member variables and properties that is language-agnostic.
The distinction is most apparent in component-oriented programming, which is useful anywhere, but easiest to understand in a graphical UI. In that context, I tend to think of the design-time configuration of a component as manipulating the "properties" of an object. For example, I choose the foreground and background colors, the border style, and font of a text input field by setting its properties. While these properties could be changed at runtime, they typically aren't. At runtime, a different set of variables, representing the content of the field, are much more likely to be read and written. I think of this information as the "state" of the component.
Why is this distinction useful? When creating an abstraction for wiring components together, usually only the "state" variables need to be exposed. Going back to the text field example, you might declare an interface that provides access to the current content. But the "properties" that control the look and feel of the component are only defined on a concrete implementation class.