On Thursday, February 02, 2012 11:11:28 Ali Çehreli wrote: > On 02/02/2012 11:00 AM, xancorreu wrote: > > Al 02/02/12 19:18, En/na bearophile ha escrit: > > > > Can I say "serialize the first, second and third arguments as Class > > Person"? > > > > I mean, if you define a class Person like: > > > > class Person { > > string name > > uint age > > dead bool > > } > > > > could you serialize the input from console, like > > Std.in.serialize(Person, args(0), args(1), args(2))? > > I haven't used it but there is Orange: > > https://github.com/jacob-carlborg/orange > > I think it will be included in Phobos. > > > You could do that "manually" checking each paramm, but it's a tedious > > task. > > If the input is exactly in the format that a library like Orange > expects, then it's easy. > > To me, constructing an object from user input is conceptually outside of > OO, because there is no object at that point yet. It makes sense to me > to read the input and then make an object from the input. > > Depending on the design, the input may be rejected by the function that > reads the input, by the constructor of the type, or by both.
I'd be very surprised if Orange could help here (though I've never used it, so I don't know exactly what it can it). Normally, when you talk about serialization, you talk about serializing an object to another format (generally a binary format of some kind) and restoring it later, not creating an object. It's pretty much expected that if you're going to create an object from user input, you're going to have to do it yourself. That's perfectly normal. What makes the most sense for each application varies too much to really standardize it - especially when you consider error handling. What happens when not enough arguments were passed to the application? What if the values given can't be converted to the desired types? etc. If you have class Person { string name; uint age; bool dead; } I'd expect something like: int main(string[] args) { if(args.length != 4) { stderr.writeln("Not enough arguments."); return -1; } auto name = args[1]; uint age; try age = to!uint(args[2]); catch(ConvException ce) { stderr.writefln("[%s] is not a valid age.", args[2]); return -1; } bool dead; try dead = to!bool(args[3]); catch(ConvException ce) { stderr.writefln("[%s] is not a valid boolean value. It must be true or false.", args[3]); return -1; } auto person = Person(name, age, dead); //... return 0; } And whether that's the best way to handle it depends on what you're trying to do in terms of user input and error messages. How on earth is all of that going to be handled generically? It all depends on what the programmer is trying to do. Switching to use command-line switches and getopt would help some, but you still have to deal with the error messages yourself. Creating the Person is the easy part. - Jonathan M Davis