I have a third party object which uses the toString method inherited from Java.lang.Object. This method is pretty useless. However I can’t think of a clean design to override this behavior. Different approaches below.
- Subclass and override the toString method.
The problem: if any calls internal to the original object call toString and inspect the returned String, they will now break. I don’t want to break the existing object, or assume anything about the cleanliness of the third-party code.
- Create a StringFactory with a createString method.This method calls toString on all objects other than my third-party object in question, but for my object builds a String in my custom way.
The problem: I can neither require that everything gets passed to the createString method and never called toString on directly (this would be ludicrous across a large code base) nor can I easily remember which objects should be passed, because there is custom logic for them.
Does anyone have a design pattern that feels clean?
Just use a static method on a util class: