3

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?

2
  • Just so you know, technically that isn't valid JSON. You would need {"factory":"Shapes.createRectangle","args":[10,20]}. Commented Aug 25, 2016 at 15:52
  • Thanks. I have fixed the JSON as you suggest. Commented Aug 25, 2016 at 16:27

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I take your point: this way needs extra work for mutable objects. I have up-ticked your answer as useful. I will wait to see if anyone else has other gotchas.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.