Using the Writable and Readable interface for a class


I would like to make a particular class I have able to be written and read to a stream / file easily, and see that Xojo provides a Writable and Readable interface. I know how to implement an interface for a class (in theory / for other languages) but would love to see an example of the proper way to do it in Xojo, and to use it for this particular case to put and get my object onto a stream. The pdf docs don’t seem to talk about class interfaces in general nor the writable / readable interface specifically.

I suppose I could also subclass BinaryStream and make my own WriteMyClass and ReadMyClass methods, but I suspect it’s better to make MyClass implement Writable and Readable.

Could anyone share a model or brief overview of the best practice for this?



I found the documentation for interfaces In Ch. 5 of Userguide-Fundamentals, and it seems that Readable and Writeable are for implementing the process of dumping the said data onto a stream of different kinds (TCPSocket, BinaryStream, etc…) and not for making a particular class be able to convert its contents to something that can be read or written to one of these streams.

And that the Read and Write methods take type String.

So perhaps I need to write a function to convert my entire class to / from a String (stream of text) in order to be able to read and write it to something that implements these interfaces?

Yes. I recommend creating ToXML and FromXML methods for the job. It will let you add and remove properties easily in the future.

And then I could just use a BinaryStream WritePString( myClassInstance.toXML() ) or myClassInstance.fromXML ( myStream.ReadPString() ) ?

And I suppose I could implement my own toXML / fromXML class interface to add to classes in general?

That seems convenient enough if that’s more or less the best practice.



Yes, that’s the right approach.

If you wanted to use the Interfaces, you would add a method to your class that took an object of that interface type as an argument:

sub WriteMyClass(w as Writable)

The you would pass whatever object you want to write to - stream, socket, whatever.

dim f as folderitem = getfolderitem("myfile")
dim b as binarystream =
dim s as new TCPSocket
s.connect ...