f# class constructor formatting - json

I am creating a program that takes an email and converts it into json. In the interest of learning functional languages I thought it would be a good opportunity to learn F#. So first off I want a message class that can then easily be serialized into json. This class will have some members that can be null. Because of these optional parameters I am using the following format
type Email(from:string, recipient:string, ?cc:string .........) =
member x.From = from
member x.Recipient = recipient.....
This class actually has a lot of members as I want to store every piece of information that an email could have. What happens is if I try to format the constructor myself by splitting it onto multiple lines I get warnings. How do people make such a gigantic constructor look good in f#? Is there a better way to do this?
On a similar note, I'm not finding visual studio very helpful for f#, what are other people using to code? I think there is a mode for emacs for example...

There should not be any warnings if all "newlined" parameters start at the same column. For example:
type Email(from:string, recipient:string,
?cc:string) =
member x.From = from
member x.Recipient = recipient
(I personally enjoy using Visual Studio for F#. I doubt there is an IDE with more complete support.)

As an alternative to creating constructor that takes all properties as parameters, you can also create an object with mutable properties and then specify only those that you want to set in the construction:
type Email(from:string, recipient:string) =
member val From = from with get, set
member val Recipient = recipient with get, set
member val Cc = "" with get, set
member val Bcc = "" with get, set
let eml = Email("me#me.com", "you#you.com", Cc="she#she.net")
This is using a new member val feature of F# 3.0. Writing the same in F# 2.0 would be pretty annoying, because you'd have to define getter and setter by hand.

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.

Dart objects with strong typing from JSON

I'm learning Dart and was reading the article Using Dart with JSON Web Services, which told me that I could get help with type checking when converting my objects to and from JSON. I used their code snippet but ended up with compiler warnings. I found another Stack Overflow question which discussed the same problem, and the answer was to use the #proxy annotation and implement noSuchMethod. Here's my attempt:
abstract class Language {
String language;
List targets;
Map website;
}
#proxy
class LanguageImpl extends JsonObject implements Language {
LanguageImpl();
factory LanguageImpl.fromJsonString(string) {
return new JsonObject.fromJsonString(string, new LanguageImpl());
}
noSuchMethod(i) => super.noSuchMethod(i);
}
I don't know if the noSuchMethod implementation is correct, and #proxy seems redundant now. Regardless, the code doesn't do what I want. If I run
var lang1 = new LanguageImpl.fromJsonString('{"language":"Dart"}');
print(JSON.encode(lang1));
print(lang1.language);
print(lang1.language + "!");
var lang2 = new LanguageImpl.fromJsonString('{"language":13.37000}');
print(JSON.encode(lang2));
print(lang2.language);
print(lang2.language + "!");
I get the output
{"language":"Dart"}
Dart
Dart!
{"language":13.37}
13.37
type 'String' is not a subtype of type 'num' of 'other'.
and then a stacktrace. Hence, although the readability is a little bit better (one of the goals of the article), the strong typing promised by the article doesn't work and the code might or might not crash, depending on the input.
What am I doing wrong?
The article mentions static types in one paragraph but JsonObject has nothing to do with static types.
What you get from JsonObject is that you don't need Map access syntax.
Instead of someMap['language'] = value; you can write someObj.language = value; and you get the fields in the autocomplete list, but Dart is not able to do any type checking neither when you assign a value to a field of the object (someObj.language = value;) nor when you use fromJsonString() (as mentioned because of noSuchMethod/#proxy).
I assume that you want an exception to be thrown on this line:
var lang2 = new LanguageImpl.fromJsonString('{"language":13.37000}');
because 13.37 is not a String. In order for JsonObject to do this it would need to use mirrors to determine the type of the field and manually do a type check. This is possible, but it would add to the dart2js output size.
So barring that, I think that throwing a type error when reading the field is reasonable, and you might have just found a bug-worthy issue here. Since noSuchMethod is being used to implement an abstract method, the runtime can actually do a type check on the arguments and return values. It appears from your example that it's not. Care to file a bug?
If this was addressed, then JsonObject could immediate read a field after setting it to cause a type check when decoding without mirrors, and it could do that check in an assert() so that it's only done in checked mode. I think that would be a nice solution.

How would Object.defineProperty be in AS3?

I'm an architect from a strong JavaScript background, but I did some .NET and Java in the past.
However, I wanted to put a hand on ActionScript3, which I was promised that is very related to JavaScript.
As a startup project I took on myself to try port to ActionScript3 one of my favorite assertion utils - should.js - that makes your test codes really pleasant to read.
Updated: 2013-02-19
I saw I confuse with my abstract speaking, so I replaced some of the post with the concrete question in mind.
Here's the full picture:
Consider the following JavaScript code:
Object.defineProperty(Object.prototype, 'should'
, { set: function(){}
, get:
function(){
return new Assertion(Object(this).valueOf());
}
, configurable: true
, enumerable : false
}
);
That is part of the implementation of the JavaScript module Should. The other part is a definition of a the class Assertion, that is constructed with a value, and implements a wide and nice set of assertion methods, against that value. Methods like like
var o = Assertion(actualValue)
o.equals(expectedValue1)
o.moreThan(expectedValue2)
o.contains(expectedValue3)
and aliases to keep english grammer
var o = Assertion(actualValue)
o.equal(expectedValue1)
o.contain(expectedValue3)
and aliases for the lazy sharpshooters, like
o.eql(expectedValue)
o.gt(expectedValue) //greater then
o.gte(...) //greater then or equal
//and so on...
and some connectors that just return this, (which is the instance of Assertion constructed with the test value) like
o.be
o.and
What does it give you?
A test code that looks like this:
var person = getPerson();
Should.exist(person); //that's a static call, and that's easy
//but these are a member calls:
person.should.have("name","age","address","friends");
person.name.should.equal("John");
person.age
.should
.be.number()
.and.be.between(20,30);
person.address
.should
.be.string().and
.startWith("\d").and
.endWith(" st.")
//or even
.and.match(/^[0-9]{1,9}\s+[A-Z][a-z0-9 ]* st\.$/);
person.friends
.should
.be.array().and
.be.between(3,5).and
.containOnlyType(String);
Isn't that wonderful? it's plain English!
You could argue about aesthetics of indentation, where to put the and, and if they are at all necessary, but besides that - anybody can read or write it:
Once you took the 'should' attribute that exists on every object but does not spoil map iterations - you can go on chaining whatever you have to claim regarding the value you started from.
It could have more nifty iteration tools, reflection utilities, be augmented with test functions relevant for your object model, and so on and so forth, but lets just get over the first step :)
But for that, you need every object in the system to feature a non-enumerable smart property called should that in it's getter function returns an Assertion object constructed with the this as the tested value.
(you ain't seen nothing yet - wait to see the beautiful rejection messages it gives! Yummie!!
So yea - I would happily sacrifice the option to call an attribute "should"... and will happily give up intelisense as well - at least as long as it's plain English)
So, in comments, bfavaretto gave us the first step - we know how to prevent enumeration of an attribute - great & thanks!!
Now, can we make it a getter-attribute who's function can access the this?
When I'm done I'm going to put it in some public repo licensed under MIT, for all of us to have fun with :)
Help anybody?
You example is actually 90% correct - but define it like actionscript, not like javascript!
You can still define prototypes in AS3 and they will still work just like prototypes in AS2. The only difference in AS3 is the compiler. AVM2 for some reason does not cast prototypes to native classes (although I didn't test custom classes).
The Prototype Trick: Cast the class as an object.
Eg: if you create:
Array.prototype.random = function():void{}
Then create the object:
var myProtoArray:Array = new Array;
2 things will happen:
myProtoArray.random() //ERROR - this will fail, AVM2 did not map the prototype to Array
but
Object(myProtoArray).random() //WORKS
random() was cast to the Object class, then mapped to Array - I have no idea why!
Hope this helps, cheers.
I confess I'm not keenly familiar with how Javascript works, but if I'm understanding defineProperties purpose correctly, it is a runtime dictation of not just what a property should be, but also the associated namespace to which it belongs (or at least what AS3 considers a namespace).
Class properties are either predefined & only modifiable via custom get() set() functions, or dynamic. Once compiled, their namespace cannot be changed (to my knowledge), so any non-private property is implicitly enumerable, and modifiable whether or not you've written getter/setters (ie: foo.a = value). According to Adobe...
Properties that you create are enumerable, but built-in properties are
generally not enumerable.
That said, you can get a complete list of properties from a class by using describeType. Quite an exhaustive amount of info can be gleaned this way, and I suspect should suit your needs if you wanted to port Mozilla's recreated defineProperties example. Below is an example printing out only property values.
function showProps(obj:*):void {
var desc:XML= describeType(obj);
// public vars
for each (var n:XML in desc.variable){
trace(n.#name + ": " + obj[n.#name]);
}
// getters
for each (n in desc.accessor){
try {
trace(n.#name + ": " + obj[n.#name]);
} catch (error:Error) {
trace("Unable to read write-only property.");
}
}
}
I hope this helps, but I'm certain I don't fully understand what you're trying to accomplish. If you could elaborate, that'd be appreciated.
Ok, guys, thanks for all the help, 22+
I'll give a summary for the people that are interested in the original question, and after that - I'll show you the outcome of my efforts.
The challange was made of two parts:
1 - prevent the augmented (=added on runtime) property from being enumerated
To the first part - thanks to #bfavaretto, commented on the question level - Object.setPropertyIsEnumerable - did the trick great.
2 - make the augmented property operate a getter function with access to the this so it can use it on the constructor of the returned value.
About this second part - Basically - I could not find a way to augment (=add) a property getter to a prototype, and have it operate on instances that enjoy it's API through the inheritance tree.
Anyway, within these limits - here's the outcome:
https://github.com/osher/should.as
Not exact porting because of the platform differences,
and I still have some methods to catch up with the original should.js (like the HTTP testing methods)
but close enough.
The main difference is that instead
var o:Object =
{ name : "Radagast"
, color: "Brown"
}
o.should.have.properties("name","color")
.and.have.property("name","Radagast");
o.name.should.not.equal("Palandoo");
o.color.should.equal("Brown");
you have to go
o.should().have.properties("name","color")
and.have.property("name","Radagast");
o.name.should().not.equal("Palandoo");
o.color.should().equal("Brown");
(the brackets - no getter possible - so the should attribute is a method, and you have to invoke it yourself)
Now if you get stuck and need help from the intellisense, you have to do this:
var should:tdd.Should = o.color.should();
should. <ctrl+space>
which kind'a takes the sting out, but for a peek in the intelisense - it helps
Important
One more thing - you have to force the static constructor of Should as soon in execution as you can,
for example, I do it here:
[Suite]
[RunWith("org.flexunit.runners.Suite")]
public class my_awsome_test_suite
{
//forces the static constructor of tdd.Should
import tdd.Should;
private static var s:Should = new Should();
public var c1:testCase1;
public var c2:testCase2;
public var c3:testCase3;
public var c4:testCase4;
}
I'll probably add some propper README.md later, and more awsome member functions to tdd.Should
Have fun

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 can I create Vectors dynamically in AS3?

I want to create a class that will mainly house a Vector. The class will have some methods that deal with items in the Vector.
The issue I am having at the moment is that I can't work out how to dynamically create an instance of Vector. So far I've tried this and similar with no luck:
public class List
{
private var _content:Vector;
public function List(type:Class)
{
_content = new Vector.<type>();
}
}
Here is how I dynamically construct a vector of BitmapData (which is required by the MouseCursorData class):
var vectorClassOfBitmapData:Class = Class(getDefinitionByName("__AS3__.vec::Vector.<flash.display::BitmapData>"));
var bitmapDataVector:* = new vectorClassOfBitmapData(1,true);
The above is the same as the compile-time:
var bitmapDataVector:* = new Vector.<BitmapData>(1, true);
In this way, you can compose the class definition string at runtime and use getDefinitionByName to dynamically construct vectors of different data types.
Not exactly what you were after, but it might help others.
This post by Paul Robertson (previously Senior ActionScript Developer/Writer at Adobe) provides a little more information on how Vectors are declared:
The Vector class allows (requires) you to specify the type it will
contain at compile time — both for variable declarations and when
creating instances.
Because the type parameter is a literal, it must be provided at compile time. In fact, every reference to a Vector is checked at compile time, with the exception of .shift() and .unshift, which are checked at run time.
Adobe's article on indexed arrays provides some more interesting information on that. In fact, it mentions that strict compile time type safety is one of the key features of Vectors.
In short: It is not possible to use a variable to set a Vector's type, because the type parameter is a literal and a compile time requirement.
Hope that helps!
Additional References:
http://www.adobe.com/devnet/flash/quickstart/programming_vectors_as3.html
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Vector.html
http://www.mikechambers.com/blog/2008/08/19/using-vectors-in-actionscript-3-and-flash-player-10/
How do generics (Vector) work inside the AVM?
Another option that might work for you is to use an interface; Vectors do not have to be concrete types. So if you can abstract out some common contract that your objects can abide by, then use that instead. For example, say you wanted a list of renderable objects, you could say:
public interface IRenderable {
function renderTo(obj:DisplayObject):void;
}
var _content:Vector.<IRenderable> = new Vector.<IRenderable>();
Then you can shove as many different concrete types into the Vector, as long as they implement the IRenderable interface. So while generics in ActionScript 3 are really just syntactic compiler sugar, like Andrew Odri said, you might be able to get around that depending on what you are specifically trying to do.
Sounds like you just need an Array! The performance is only improved with a Vector<> because the type is sorted out at compile time. If you want a "dynamic" type, then you should use an Array.
The original question is a couple years old, but I felt like sharing this because it might help others.
It's inspired upon Matthew Peterson's answer but it assumes a little less about the internal class names (it only assumes the .<> syntax).
function CreateVectorOf(subtype:Class)
{
var vecname:String = getQualifiedClassName(Vector);
var subname:String = getQualifiedClassName(subtype);
var vecclass:Class = getDefinitionByName(vecname + ".<" + subname + ">") as Class;
return new vecclass();
}