Is there a way to pseduo-subclass Strings, Numbers, uint, ints, or other 'final' primitives in Actionscript 3 using the Proxy class? - actionscript-3

It seems like there might be a way, but I'm not seeing it. I have, in the past, used the valueOf() and toString() methods on Object to cause custom objects to behave in numbers or strings based on context, but I'd like to do more.

Basically no. Final is final so they cannot be extended. You could make a class which has all the same methods as the Number class, but it still wouldn't BE a Number as far as the compiler is concerned.
To be honest there should never be a reason that you should need to extend from these classes.
As far as proxies go you could consider making a factory class which returns a pre-formatted string/number eg:
var myString:String= StringFactory.asCurrency("50"); // "$50.00"

as already stated by groady, this is not possible ... also not in the scenarios you described ... but the thing is, that at runtime, the type detection mechanism is pretty easy ... lookup the traits object, and check whether it matches a class/subclass, or whether it explicitely implements and interface ... in any other case, you will have errors ... you can use proxies to implement your own array access ... however, they will not be arrays, thus passing them to a function that expects Array, will cause errors ... also, in AS3 you cannot overload operators, so you will really have a hard time ... you could create a class for numeric values, but then manipulating it would require methods as add, subtract etc. ... there is however a related request on jira ... still, this will not solve your problem entirely, because you cannot control the way an object responds to operators ... if you compile in ECMA compatibility mode, you probable will be able to bypass the strict runtime type checks, but on the other hand, you will lose a lot of speed ... the best thing probably really is creating a class that has to be manipulated through methods instead of operators ... not too comfortable, but the best AS3 offers ...
greetz
back2dos

Related

Scalaz.NonEmptyList vs Scala.List?

Can someone explain why should I use Scalaz's NonEmptyList over Scala's List?
In a immutable application it does not make much sense to create an empty List
So should I always use NonEmptyList in an immutable application ?
Why else would I use scalaz's NonEmptyList over scala's Listother than the obvious reason that it guarantee at least one element in the list ?
Scala's collections have a number of unsafe methods. These include head, last etc. Unsafe means they will throw an exception if the collection is empty. Now you can say "I am really sure this collection will not be empty at runtime, so my code is safe". However, somebody comes along, changes your the code etc.
So, essentially, that scalaz type gives you static safety, because if you statically know that the collection will not be empty, then it is safe to call head etc.

What are better ways to create a method that takes many arguments? (10+?)

I was looking at some code of a fellow developer, and almost cried. In the method definition there are 12 arguments. From my experience..this isn't good. If it were me, I would have sent in an object of some sort.
Is there another / more preferred way to do this (in other words, what's the best way to fix this and explain why)?
public long Save (
String today,
String name,
String desc,
int ID,
String otherNm,
DateTime dt,
int status,
String periodID,
String otherDt,
String submittedDt
)
ignore my poor variable names - they are examples
It highly depends on the language.
In a language without compile-time typechecking (e.g. python, javascript, etc.) you should use keyword arguments (common in python: you can access them like a dictionary passed in as an argument) or objects/dictionaries you manually pass in as arguments (common in javascript).
However the "argument hell" you described is sometimes "the right way to do things" for certain languages with compile-time typechecking, because using objects will obfuscate the semantics from the typechecker. The solution then would be to use a better language with compile-time typechecking which allows pattern-matching of objects as arguments.
Yes, use objects. Also, the function is probably doing too much if it needs all of this information, so use smaller functions.
Use objects.
class User { ... }
User user = ...
Save(user);
It decision provides easy way for adding new parameters.
It depends on how complex the function is. If it does something non-trivial with each of those arguments, it should probably be split. If it just passes them through, they should probably be collected in an object. But if it just creates a row in a table, it's not really big deal. It's less of a deal if your language supports keyword arguments.
I imagine the issue you're experiencing is being able to look at the method call and know what argument is receiving what value. This is a pernicious problem in a language like Java, which lacks something like keyword arguments or JSON hashes to pass named arguments.
In this situation, the Builder pattern is a useful solution. It's more objects, three total, but leads to more comprehensible code for the problem you're describing. So the three objects in this case would be as such:
Thing: stateful entity, typically immutable (i.e. getters only)
ThingBuilder: factory class, creates a Thing entity and sets its values.
ThingDAO: not necessary for using the Builder pattern, but addresses your question.
Interaction
/*
ThingBuilder is a static inner class of Thing, where each of its
"set" method calls returns the ThingBuilder instance being worked with
while the final "build()" call returns the instantiated Thing instance.
*/
Thing thing = Thing.createBuilder().
.setToday("2012/04/01")
.setName("Example")
// ...etc...
.build();
// the Thing instance as get methods for each property
thing.getName();
// get your reference to thingDAO however it's done
thingDAO.save(thing);
The result is you get named arguments and an immutable instance.

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.

How should I design a method that allows for optional operations?

For example, suppose I this:
class Gundam00 extends Gundam implements MobileSuit {
...
public void fight(final List<MobileSuit> mobiruSuitso, final List<Gundam> theOtherDudes, final List<Person> casualities) {
....
}
}
Suppose theOtherDudes and casualities parameters are optional. How can I make this method as clean as possible? I thought about having booleans indicating if they're null, and then checking them as needed.
I could also have different versions of the method for each combination of parameters but there would be a lot of code duplication I think.
Any suggestions?
I find that past 2-3 arguments, the ability to remember what all the arguments to a function are suffers. And comprehensibility along with it.
Passing named arguments can help. Languages with a convenient hash-like literal syntax make this really easy. Take JavaScript:
g = new Gundam00();
g.fight({opponent: enemy, casualties: 'numerous'});
You can also take advantage of variable length argument features to work this in (treat odd arguments as names, even arguments as the actual parameters).
g.fight('opponent',enemy,'casualties', 'numerous');
And some languages actually support named arguments straight-out (see: http://en.wikipedia.org/wiki/Named_parameter#Use_in_programming_languages ).
Finally, you might want to consider adding other methods for this using what some call a Fluent Interface (http://en.wikipedia.org/wiki/Fluent_interface ). Basically, you've got method call which return the object itself, so you can chain calls together:
g.opponent(enemy).casualties('numerous').fight();
This might be the easiest option if you're working in a manifestly/statically-typed class-focused language.
Update
Responding to Setsuna's comment... in that last example, if you've got the luxury, you can make methods like opponent and casualties simple setters that don't affect any internal state or computation in any other way than setting a parameter for which they're named. They simply set internal properties up, and then all of the real work happens inside action methods like fight.
If you can't do that (or if you don't like writing methods whose operations are sub-atomic), you could stake out a half-way spot between this idea with the hash-like literal idea, and create your own collection class specifically for invoking named arguments:
n = new NArgs();
g.fight(n.arg('opponent',enemy).arg('casualties','numerous').arg('motion','slow'));
A little more unwieldy, but it separates out the named arguments problem and lets you keep your methods a bit more atomic, and NArgs is probably something you could implement pretty easily just wrapping some methods around one type of Collection (HashTable?) or another that's available in your language.
Add the methods. Overloading methods is generally an antipattern and a refactoring opportunity for someone else.
http://www.codinghorror.com/blog/2007/03/curlys-law-do-one-thing.html
I thought about having booleans indicating if they're null, and then checking them inside and reacting accordingly.
Or ... you could just check if they're null.
if(theOtherDudes == null)
...
If there is only one "main method" in your class, then you can implement the optional arguments as getter/setter functions. Example:
public void setOtherDudes(final List<Gundam> theOtherDudes) {} // for input arguments
public List<Person> getCasualities() {} // for output arguments
And then, in your documentation, mention that if the caller has any optional input arguments it has to be passed in before calling fight(), and the optional output values will be available when fight() has been called.
This is worthwhile if there are dozens of optional arguments. Otherwise, I suggest overloading the method as the simplest way.

Why all the functions from object oriented language allows to return only one value (General)

I am curious to know about this.
whenever I write a function which have to return multiple values, either I have to use pass by reference or create an array store values in it and pass them.
Why all the Object Orinented languages functions are not allowed to return multiple parameters as we pass them as input. Like is there anything inbuilt structure of the language which is restricting from doing this.
Dont you think it will be fun and easy if we are allowed to do so.
It's not true that all Object-Oriented languages follow this paradigm.
e.g. in Python (from here):
def quadcube (x):
return x**2, x**3
a, b = quadcube(3)
a will be 9 and b will be 27.
The difference between the traditional
OutTypeA SomeFunction(out OutTypeB, TypeC someOtherInputParam)
and your
{ OutTypeA, OutTypeB } SomeFunction(TypeC someOtherInputParam)
is just syntactic sugar. Also, the tradition of returning one single parameter type allows writing in the easy readable natural language of result = SomeFunction(...). It's just convenience and ease of use.
And yes, as others said, you have tuples in some languages.
This is likely because of the way processors have been designed and hence carried over to modern languages such as Java or C#. The processor can load multiple things (pointers) into parameter registers but only has one return value register that holds a pointer.
I do agree that not all OOP languages only support returning one value, but for the ones that "apparently" do, this I think is the reason why.
Also for returning a tuple, pair or struct for that matter in C/C++, essentially, the compiler is returning a pointer to that object.
First answer: They don't. many OOP languages allow you to return a tuple. This is true for instance in python, in C++ you have pair<> and in C++0x a fully fledged tuple<> is in TR1.
Second answer: Because that's the way it should be. A method should be short and do only one thing and thus can be argued, only need to return one thing.
In PHP, it is like that because the only way you can receive a value is by assigning the function to a variable (or putting it in place of a variable). Although I know array_map allows you to do return something & something;
To return multiple parameters, you return an single object that contains both of those parameters.
public MyResult GetResult(x)
{
return new MyResult { Squared = Math.Pow(x,2), Cubed = Math.Pow(x,3) };
}
For some languages you can create anonymous types on the fly. For others you have to specify a return object as a concrete class. One observation with OO is you do end up with a lot of little classes.
The syntactic niceties of python (see #Cowan's answer) are up to the language designer. The compiler / runtime could creating an anonymous class to hold the result for you, even in a strongly typed environment like the .net CLR.
Yes it can be easier to read in some circumstances, and yes it would be nice. However, if you read Eric Lippert's blog, you'll often read dialogue's and hear him go on about how there are many nice features that could be implemented, but there's a lot of effort that goes into every feature, and some things just don't make the cut because in the end they can't be justified.
It's not a restriction, it is just the architecture of the Object Oriented and Structured programming paradigms. I don't know if it would be more fun if functions returned more than one value, but it would be sure more messy and complicated. I think the designers of the above programming paradigms thought about it, and they probably had good reasons not to implement that "feature" -it is unnecessary, since you can already return multiple values by packing them in some kind of collection. Programming languages are designed to be compact, so usually unnecessary features are not implemented.