I have some object model(e.g. commands) which can be marshaled to some textual representation. I have two options:
- Assume that every subclass of Command will correctly override “toString”
- Create interface with “marshal” and “unmarshal” methods that every child will be ought to implement.
Which option is better for such delegation? I mean, toString has really close meaning, but it doesn’t give me a guarantee that child class just doesn’t use standard implementation of toString.
Thanks
I think the approach with explicit methods is far superior. You’ve pretty much nailed the reasons:
Every single maintenance programmer to touch the code will need to be aware of this assumption. If they suddenly decide that it would be nice that some class’s
toString()included an additional piece of information (say for debugging), the code will unexpectedly break.This makes the API explicit, hard to fail to implement, and much harder to accidentally break or misuse.
It also means that certain errors can be caught at compile time. You can have a method that takes
IMarshallable, and the compiler won’t let you pass anything that doesn’t implement the interface. With the first approach, every object has atoString()method, and there’s no way for the compiler to know whether a particular object’stoString()implements your marshalling protocol. This means that it can’t diagnose this type of error at compile time.