Posted Mon, 20 Jun 2016 17:14:28 GMT in reply to
zunkree
Reply
On Mon, 13 Jun 2016 13:25:50 GMT, zunkree wrote:
On Mon, 22 Dec 2014 12:23:59 GMT, Jack Applegame wrote:
On Mon, 22 Dec 2014 10:41:10 GMT, Mathias LANG wrote:
Okay. I can't see why you would use it (looks like lack of SoC), could you provide an use case ?
I just don't want to serialize data with default values. This is useless overhead (extra network traffic and CPU load).
Okay. I can't see why you would use it (looks like lack of SoC), could you provide an use case ?
Anyway, I can imagine something like this fitting into Vibe.d:
struct MyStruct {
@optional(canSerialize) int value;
bool canSerialize(int value) { return value != 42; }
}
Here, 'MyStruct.value' will only be serialized if the return value from canSerialize (which can be either a member or a free function) is true. Would that do ?
Good idea. Like attributes for web interfaces:
struct MyStruct {
bool canSerialize() { return this.value != 42; }
@optional!canSerialize int value = 42;
}
Does vibe.d support that approach?
Not currently. It can be worked around somewhat by providing a custom toRepresentation
method:
struct MyStruct {
int value = 42;
Json[string] toRepresentation() {
Json[string] ret;
if (value != 42) ret["value"] = value;
return ret;
}
static MyStruct fromRepresentation(Json[string] j)
{
MyStruct ret;
if (auto pv = "value" in j)
ret.value = pv.get!int;
return ret;
}
}
Instead of the @optional!canSerialize
another (or an additional) possibility would be to handle @optional Nullable!int value;
in that way.
Of course, skipping the value if it equals .init
, like suggested in the OP, is also a possibility.
Any further opinions or use cases?