Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Design pattern to "toString" a third party object

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.

  1. 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.

  1. 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?

like image 898
Cory Kendall Avatar asked Dec 17 '22 09:12

Cory Kendall


2 Answers

Just use a static method on a util class:

public class MyUtils {

    public static String toString(My3rdPartyClass obj) {
        // impl here
    }
}
like image 182
Bohemian Avatar answered Dec 27 '22 06:12

Bohemian


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
    }
}
like image 35
corsiKa Avatar answered Dec 27 '22 05:12

corsiKa