Lately I've started adding this to certain classes in an in-house API:
public class MyClass {
// I usually do this with classes I expect to
// be printed out or tested a lot (particularly
// in the early stages of creating the class/package).
//
// Having one field is not a criteria for doing this,
// just a simple example. And of course there is always
// a default value for the toString field.
private Object oneOtherFieldExample;
private Function<MyClass, String> toString =
myClass -> String.valueOf(oneOtherFieldExample);
...
public void setToString(Function<MyClass,String> toStringFunction) {
toString = toStringFunction;
}
public String toString() {
return toString.apply(this);
}
This has come in handy a couple times but since I'm working on an in-house API I'm wondering
- Do you all foresee any potential issues I'm missing?
- Is this reasonably legible and intuitive?
- Does this or something similar already exist as some kind of pattern (and if so, what is it called)?
- Since this is especially used for testing and early building, should I add a static way to set the default toString variable to avoid having to set it manually every time I instantiate a new MyClass Object (in the case where thousands are being created)?
...stream().peek(System.out::println)...
). Then it just occurred to me that since it's part of an API, an easy way to modify how/what it prints when testing could be helpful. – roundar Nov 19 '15 at 17:29new MyClass() { @Override public void toString() { ... } };
Which wouldn't be worth doing, but if you could create a few variables with different printing methods for different scenarios you could just:if(something) mc.setToString(functionA); else mc.setToString(functionB);
– roundar Nov 19 '15 at 17:39