Actionscript 3 - passing custom class as parameter to custom class where parameter class not constructed - actionscript-3

Hi and thanks in advance,
I have a custom class being constructed from my main class. In the custom class it has another custom class that is passed in as a parameter. I would like to strictly type the parameter variable but when I do, 'the type is not a compile type constant etc'.
This, I understand, is because the custom class used as a parameter has not yet been constructed.
It all works when I use the variable type ( * ) to type the parameter.
I suspect this is a design flaw, in that I am using an incorrect design pattern. It is actually hand-me-down code, having received a large project from someone else who is not entirely familiar with oop concepts and design patterns.
I have considered using a dummy constructor for the parametered class in my main class but the passed in class also takes a custom class (itself with a parametered constructor). I am considering using ... (rest) so that the custom classes' parameters are optional.
Is there any other way to control the order of construction of classes? Would the rest variables work?
Thanks
(edit)
in main.as within the constructor or another function
var parameter1:customclass2;
customclass1(parameter1);
in customclass1 constructor:
public function customclass1(parameter1:customclass2)
{
....
Flash complains that the compiled type cannot be found when I use the data type customclass 2 in the paramater. It does not complain when I use the variable data type * or leave out the data type (which then defaults to * anyway). I reason that this is because customclass2 has not yet been constructed and is therefore not available to the compiler.
Alternatively, I have not added the path of customclass2 to the compiler but I am fairly certain I have ruled this out.
There are over 10,000 lines of code and the whole thing works very well. I am rewriting simply to optimise for the compiler - strict data typing, error handling, etc. If I find a situation where inheritance etc is available as an option then I'll use it but it is already divided into classes (at least in the main part). It is simply for my own peace of mind and to maintain a policy of strict data typing so that compiler optimization works more efficiently.
thnx

I have not added the path of customclass2 to the compiler but I am fairly certain I have ruled this out.
So if you don't have the class written anywhere what can the compiler do ? It is going to choke of course. You either have to write the CustomClass class file or just use "thing:Object" or "thing:Asteriks". It's not going to complain when you use the "*" class type because it could be anything an array, string, a previously declared class. But when you specify something that doesn't exists it will just choke, regardless of the order the parameters are declared in.

Related

kotlin, how to simplify passing parameters to base class constructor?

We have a package that we are looking to convert to kotlin from python in order to then be able to migrate systems using that package.
Within the package there are a set of classes that are all variants, or 'flavours' of a common base class.
Most of the code is in the base class which has a significant number of optional parameters. So consider:
open class BaseTree(val height:Int=10,val roots:Boolean=true, //...... lots more!!
class FruitTree(val fruitSize, height:Int=10, roots:Boolean=true,
// now need all possible parameters for any possible instance
):BaseTree(height=height, roots=roots //... yet another variation of same list
The code is not actually trees, I just thought this was a simple way to convey the idea. There are about 20 parameters to the base class, and around 10 subclasses, and each subclass effectively needs to repeat the same two variations of the parameter list from the base class. A real nightmare if the parameter list ever changes!
Those from a Java background may comment "20 parameters is too many", may miss that this is optional parameters, the language features which impacts this aspect of design. 20 required parameters would be crazy, but 10 or even 20 optional parameters is not so uncommon, check sqlalchemy Table for example.
In python, you to call a base class constructor you can have:
def __init__(self, special, *args, **kwargs):
super().__init(*args, **kwargs) # pass all parameters except special to base constructor
Does anyone know a technique, using a different method (perhaps using interfaces or something?) to avoid repeating this parameter list over and over for each subclass?
There is no design pattern to simplify this use case.
Best solution: Refactor the code to use a more Java like approach: using properties in place of optional parameters.
Use case explained: A widely used class or method having numerous optional parameters is simply not practical in Java, and kotlin is most evolved as way of making java code better. A python class with 5 optional parameters, translated to Java with no optional parameters, could have 5! ( and 5 factorial is 60) different Java signatures...in other words a mess.
Obviously no object should routinely be instanced with a huge parameter list, so normall python classes only evolve for classes when the majority of calls do not need to specify these optional parameters, and the optional parameters are for the exception cases. The actual use case here is the implementation of a large number of optional parameters, where it should be very rare for any individual object to be instanced using more than 3 of the optional parameter. So a class with 10 optional parameters that is used 500 times in an application, would still expect 3 of the optional parameters to be the maximum ever used in one instance. But this is simply a design approach not workable in Java, no matter how often the class is reused.
In Java, functions do hot have optional parameters, which means this case where an object is instanced in this way in a Java library simply could never happen.
Consider an object with one mandatory instance parameter, and five possible options. In Java these options would each be properties able to be set by setters, and objects would then be instanced, and the setter(s) called for setting any relevant option, but infrequently required change to the default value for that option.
The downside is that these options cannot be set from the constructor and remain immutable, but the resultant code reduces the optional parameters.
Another approach is to have a group of less 'swiss army knife' objects, with a set of specialised tools replacing the one do-it-all tool, even when the code could be seen as just slightly different nuances of the same theme.
Despite the support for Optional parameters in kotlin, The inheritance structure in kotlin is not yet optimised for heavier use of this feature.
You can skip the name like BaseTree(height, roots) by put the variable in order but you cannot do things like Python because Python is dynamic language.
It is normal that Java have to pass the variables to super class too.
FruitTree(int fruitSize, int height, boolean root) {
super(height, root);
}
There are about 20 parameters to the base class, and around 10 subclasses
This is most likely a problem of your classes design.
Reading your question I started to experiment myself and this is what I came up with:
interface TreeProperties {
val height: Int
val roots: Boolean
}
interface FruitTreeProperties: TreeProperties {
val fruitSize: Int
}
fun treeProps(height: Int = 10, roots: Boolean = true) = object : TreeProperties {
override val height = height
override val roots = roots
}
fun TreeProperties.toFruitProperty(fruitSize: Int): FruitTreeProperties = object: FruitTreeProperties, TreeProperties by this {
override val fruitSize = fruitSize
}
open class BaseTree(val props: TreeProperties)
open class FruitTree(props: FruitTreeProperties): BaseTree(props)
fun main(args: Array<String>){
val largTree = FruitTree(treeProps(height = 15).toFruitProperty(fruitSize = 5))
val rootlessTree = BaseTree(treeProps(roots = false))
}
Basically I define the parameters in an interface and extend the interface for sub-classes using the delegate pattern. For convenience I added functions to generate instances of those interface which also use default parameters.
I think this achieves the goal of repeating parameter lists quite nicely but also has its own overhead. Not sure if it is worth it.
If your subclass really has that many parameters in the constructur -> No way around that. You need to pass them all.
But (mostly) it's no good sign, that a constructor/function has that many parameters...
You are not alone on this. That is already discussed on the gradle-slack channel. Maybe in the future, we will get compiler-help on this, but for now, you need to pass the arguments yourself.

How to write a wrapper class / Override configuration in pre existing Puppet Class

I would like to override the values of another class in another Puppet Modules. Please help me by suggesting ways.
Existing Class : ( Module Name : MySQL )
class mysql::server (
$config_file = $mysql::params::config_file,
$includedir = $mysql::params::includedir)
{
My Code Logics
}
My Current Class : ( Module Name : Profiles )
Class profiles::mysql () {
class { '::mysql::server':
config_file => '/opt/arunraj',
includedir => true
}
}
When i am doing like above, I am getting duplicate class declaration error. Which is a best way to override a values between two classes
In the first place, your example code is incomplete. You present the definitions of classes mysql::server and profiles::mysql, and the latter contains a resource-style declaration of class mysql::server, but you say nothing about the one or more other declarations of class mysql::server that the given one collides with. What you actually presented is not enough to produce the error you describe.
Note also that using resource-style class declarations is usually poor form, especially for declaring public classes of any module, and most especially for declaring classes belonging to a different module than the one in which the declaration appears. The reasons are a bit technical, but to a large extent they boil down to the risk of eliciting exactly the kind of error you encountered. That happens whenever Puppet evaluates a resource-style declaration of a class for which a declaration (in any style) has already been evaluated, because class parameter values are bound as part of evaluating the first-encountered declaration.
The best way to customize class parameter values is to rely on automatic data binding (Hiera) to bind values to those parameters in the first place. If you have an oddball machine that needs different parameter values then you set them at a higher-priority level of your data hierarchy than the one from which the ordinary values come, and which is scoped narrowly enough to avoid affecting machines that should have the ordinary parameters.
Moreover, to avoid the kind of error you describe, you should also be certain everywhere to use only include-like declarations for any class that might be declared more than once (i.e. any public one, and some private ones). That goes hand in hand with automatic binding because if you don't use resource-like declarations then automatic data binding is your best available means for customizing class parameter values. The classical include-style declaration is via the include function itself, but the require, contain, and hiera_include functions also provide include-style declarations (with various differences in semantics). If you're using an ENC to declare classes then it might produce either style.

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.

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.

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.