What are the pros/cons of having a serialization function accept a sink:
class Foo:
def toString(self, stringIOSink):
pass
def toBytes(self, byteSink):
pass
versus having the serialisation function return the result:
class Foo:
def toString(self):
# ..
return s
def toBytes(self):
# ..
return bytes
(obviously this approach is the standard when serialising to string)
I've seen both in the wild and up until now have never given it much thought. Note my examples are in python, but I'm asking in a language agnostic context.
Considerations I've thought of:
accepting a sink
- implementation does not need to allocate memory (and thus client does not need to worry about how memory is managed)
- can stream output
returning result
- arguably simpler
- allows you to further manipulate/use the returned result. EG if we are serializing to JSON (similar to Python's JSON decoding operation), then if
Foo
holds a list ofBar
objects, then we can implementFoo
'stoJSON
method by:
def toJSON(self):
return {
# other members here
"bars": [b.toJSON() for b in self.bars],
}
Which wouldn't be possible if toJSON
accepted some sort of JSON sink.