Nonetheless, it should be fairly easy to implement optional parameters
across languages, using method overloading in those languages that don't
directly support optional parameters.
Thrift:
void function foo(1:i32 a, 2:i32 b = -1)
C#/Java:
public void foo(int a)
{
foo(a, -1);
}
public void foo(int a, int b)
PHP:
public function foo($a, $b = -1)
You are correct about it being impossible to disambiguate a
default-value from one not set, but aside from that this should work in
every language.
--Jonathan
Mark Slee wrote:
Yeah there's really no way to do this in most languages that don't support
variable args. For instance, consider C++ and Java
void myMethod(int x)
There's just no way to make x optional. An integer variable x simply MUST be
passed into this function. You can provide a default value if you like and not
set it yourself, but there's no getting around the argument being present.
If your application needs to disambiguate between a default-value and absence
of an argument, then you must use a struct and inspect the isset field directly.
-----Original Message-----
From: Matthieu Imbert [mailto:[email protected]]
Sent: Wednesday, July 01, 2009 11:14 AM
To: [email protected]
Subject: Re: optional fields in function declaration
Bryan Duxbury wrote:
I would say that there's no question it would be useful. However, I'm
not sure how that would translate to all client languages.
A completely safe and reliable way to simulate this would be to make a
new struct for your method that has optional fields and just use that as
the only parameter to the method. Does that make sense?
Yes, i'm already doing this and it works great. The only two drawbacks
is that you end up with a lot of structs if you have lots of functions
with optional parameters, and of course the client API is not as simple
and straightforward to use.