Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialise polymorphic JavaScript objects

Conceptually, my app has an interface and many objects that implement the interface in different ways. The objects will be created by various factory methods, and there will be more factories in future as my app evolves.

For example

var Shapes={};
var Shapes.createCircle=function(radius) {
  return {draw:function...}
};
var Shapes.createRectangle=function(width,height) {
  return {draw:function...}
};

I want to serialize these shapes in files. I plan to make each object store the name of its factory (e.g. "Shapes.createRectangle") and an array of arguments (e.g [10,20]), and then save these parts as a JSON string. That way, the deserialized objects can have all their functions restored, as well as their properties.

For example, to save an object I plan to store the JSON string

{"factory":"Shapes.createRectangle","args":[10,20]}

and then reconstruct the object in a future sessions by dynamically calling the factory method again.

Does this method of serializing polymorphic objects have any gotchas?

like image 422
Adam Gawne-Cain Avatar asked Mar 27 '26 11:03

Adam Gawne-Cain


2 Answers

Potentially. It will only work if these objects are immutable or if the only way you can change their state is reversible back into the factory arguments.

This tends to prove tricky as an api grows, but isn't impossible. I would check if an object has a serialize and deserialize method and invoke those, so you have a nice pattern how to customize serialization behavior if you need it in the future.

like image 72
Jakub Hampl Avatar answered Mar 28 '26 23:03

Jakub Hampl


One drawback is, that you're hard-coding the factory function names into your data. Of course that's only a problem if you later decide to change them... Maybe just storing the object type would be more resilient to such problems.

like image 32
fishgen Avatar answered Mar 28 '26 23:03

fishgen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!