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.
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.
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:
public class MyUtils {
public static String toString(My3rdPartyClass obj) {
// impl here
}
}
I really like Bohemian's answer.
With that in mind, an OOP way to solve it would be
class My3rdPartyClassFormatter {
private My3rdPartyClass data;
public My3rdPartyClassFormatter(My3rdPartyClass d) { this.data = d; }
public String toString() {
// impl here
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With